package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hustcad.plm.caddocapi.service.TyplmCADRelObjectService;
import com.hustcad.plm.configbom.service.change.ChangeRequestAdapter;
import com.hustcad.plm.pdm.common.model.vo.iteration.CommonIteratorVO;
import com.hustcad.plm.pdm.common.model.vo.search.ResultEntityVO;
import com.hustcad.plm.pdm.doc.vo.DocDetails;
import com.hustcad.plm.pdm.ec.module.dto.*;
import com.hustcad.plm.pdm.ec.module.vo.*;
import com.hustcad.plm.pdm.ec.service.TyplmChgNoticeQueryService;
import com.hustcad.plm.pdm.ec.service.TyplmEcAgainstDataService;
import com.hustcad.plm.pdm.ec.service.TyplmEngineeringChangeService;
import com.hustcad.plm.pdm.enumeration.service.TyplmEnumerationService;
import com.hustcad.plm.pdm.file.handler.response.ResponseResult;
import com.hustcad.plm.pdm.file.service.TyplmFileHandleService;
import com.hustcad.plm.pdm.filevault.model.vo.FileDataVO;
import com.hustcad.plm.pdm.flowbusiness.model.entity.*;
import com.hustcad.plm.pdm.iba.service.impl.TyplmAttributeServiceImpl;
import com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService;
import com.hustcad.plm.pdm.partbom.dto.PartUsageLink;
import com.hustcad.plm.pdm.partbom.service.*;
import com.hustcad.plm.pdm.partbom.vo.AlternateInfoVO;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.partbom.vo.QueryDescribeObjVO;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerView;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;
import com.lark.oapi.okhttp.*;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.entity.part.PartUsageLinkDO;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.common.CommonService;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.constant.RTPlmConstant;
import cqrtplm.dto.RtCfgStatusDTO;
import cqrtplm.entity.*;
import cqrtplm.mapper.*;
import cqrtplm.service.RTChangeRelatedService;
import cqrtplm.service.RtCfgStatusInfoService;
import cqrtplm.util.CommonUtil;
import cqrtplm.vo.TemplateInfoVO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@SuppressWarnings("JvmLinesOfCodeInspection")
@Service
@Slf4j
public class RTChangeRelatedServiceImpl implements RTChangeRelatedService {
    @Resource
    private RTChangeMapper rtChangeMapper;
    @Resource
    private RtCfgMzMapper rtCfgMzMapper;
    @Resource
    private TyplmWorkFlowContainerService typlmWorkFlowContainerService;
    @Resource
    private TyplmEcAgainstDataService typlmEcAgainstDataService;
    @Resource
    private TyplmPartRelObjectService typlmPartRelObjectService;
    @Resource
    private TyplmPdmPartService typlmPdmPartService;
    @Resource
    private TyplmFileHandleService fileHandleService;
    @Resource
    private TyplmPartDescribeLinkService typlmPartDescribeLinkService;
    @Resource
    private RTAccreditationPatternMapper dspfAccreditationPatternMapper;
    @Resource
    private RtZdMapper rtZdMapper;
    @Resource
    private RtChangeaffectChangeobjectMapper rtChangeaffectChangeobjectMapper;
    @Resource
    private RtChangeaffectAppointMapper rtChangeaffectAppointMapper;
    @Resource
    private RtChangeaffectAuthenticationMapper rtChangeaffectAuthenticationMapper;
    @Resource
    private RtChangeaffectDrawingdocumentMapper rtChangeaffectDrawingdocumentMapper;
    @Resource
    private RtChangeaffectEbomMapper rtChangeaffectEbomMapper;
    @Resource
    private RtChangeaffectFinishedbomMapper rtChangeaffectFinishedbomMapper;
    @Resource
    private RtChangeaffectInventoryMapper rtChangeaffectInventoryMapper;
    @Resource
    private RtChangeaffectModuleMapper rtChangeaffectModuleMapper;
    @Resource
    private RtChangeaffectAssociatedbomMapper rtChangeaffectAssociatedbomMapper;
    @Resource
    private TyplmChgNoticeQueryService typlmChgNoticeQueryService;
    @Resource
    private TyplmEngineeringChangeService typlmEngineeringChangeService;
    @Resource
    private TyplmEnumerationService typlmEnumerationService;
    @Resource
    private TyplmPartUsageLinkService typlmPartUsageLinkService;
    @Resource
    private ChangeRequestAdapter changeRequestAdapter;
    @Resource
    private RtCfgStatusInfoService rtCfgStatusInfoService;
    @Resource
    private TyplmAttributeServiceImpl typlmAttributeService;
    @Resource
    private TyplmCADRelObjectService typlmCADRelObjectService;
    @Resource
    private TyplmPartBomService typlmPartBomService;
    @Resource
    private CommonService commonService;
    @Resource
    private RtCfgStatusInfoMapper rtCfgStatusInfoMapper;
    @Resource
    private TyplmPartAlternateService typlmPartAlternateService;
    @Resource
    private RtChangeLockInfoMapper rtChangeLockInfoMapper;
    //机型内部名称
    @Value("${STATUS_INFO_PARTTYPE}")
    private String STATUS_INFO_PARTTYPE;
    //开发令
    @Value("${STATUS_INFO_DEVCODE}")
    private String STATUS_INFO_DEVCODE;
    @Value("${sap.sourceList.username:test}")
    private String sapSourceListUsername;
    @Value("${sap.sourceList.password.:po654321}")
    private String sapSourceListPassword;
    @Value("${sap.sourceList.url:http://116.63.169.18:50000/RESTAdapter/qas/DSPF/SI_ZMM_DSPF2SAP_SOURCESLCT_SREQ}")
    private String sapSourceListUrl;
    @Value("${sap.orderList.username:test}")
    private String sapOrderListUsername;
    @Value("${sap.orderList.password.:po654321}")
    private String saporderListPassword;
    @Value("${sap.orderList.url:http://116.63.169.18:50000/RESTAdapter/qas/CRM/ZSD_CRM2SAP_008}")
    private String sapOrderListUrl;
    @Value("${sap.orderList.username:test}")
    private String crmOrderListUsername;
    @Value("${crm.orderList.password.:po654321}")
    private String crmorderListPassword;
    @Value("${crm.orderList.url:http://192.168.102.2:7002/RatoDataApi/CrmApi/GetCRMOrderList}")
    private String crmOrderListUrl;
    //工厂视图
    @Value("${factory.view}")
    private String factoryView;

    /**
     * @param code
     * @return ibaJsonList
     */
    @Override
    public List<JSONObject> getCustomerByCode(String code, String type) throws Exception {
        List<JSONObject> ibaJsonList = new ArrayList<>();
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(code)) {
            List<JSONObject> patternCodeList = new ArrayList<>();
            if (type.equalsIgnoreCase("PatternCode")) {
                patternCodeList = this.rtChangeMapper.queryMaterialCode(code, "MaterialCode", RTPlmConstant.VIEW_DESIGN);
            } else if (type.equalsIgnoreCase("MaterialCode")) {
                JSONObject jsonObject = this.rtChangeMapper.queryMaterialByCodeAndType(code, "MaterialCode", RTPlmConstant.VIEW_DESIGN);
                patternCodeList.add(jsonObject);
            }
            if (patternCodeList != null && !patternCodeList.isEmpty()) {
                for (JSONObject obj : patternCodeList) {
                    String PARTNUMBER = obj.getString("PARTNUMBER");
                    String NAME = obj.getString("NAME");
                    List<JSONObject> parentList = new ArrayList<>();
                    queryParentPartByType(parentList, PARTNUMBER, 0);
                    if (CollUtil.isNotEmpty(parentList)) {
                        for (JSONObject parentJson : parentList) {
                            String oid = parentJson.getString("OID");
                            String ProductCode = parentJson.getString("PARTNUMBER");
                            String DevelopmentOrder = this.rtChangeMapper.queryIBAValue(oid, "DevelopmentOrder");
                            JSONObject resultJson = new JSONObject();
                            resultJson.put("PatternCode", code);
                            resultJson.put("name", NAME);
                            resultJson.put("MaterialCode", PARTNUMBER);
                            resultJson.put("ProductCode", ProductCode);
                            resultJson.put("customer", StringUtils.isEmpty(DevelopmentOrder) ? "" : DevelopmentOrder);
                            ibaJsonList.add(resultJson);
                        }
                    }
                }
            }
        }
        return ibaJsonList;
    }

    /**
     * @param workFlowContainerId
     * @return
     * @throws Exception
     */
    @Override
    public String checkCompleteDraw(String workFlowContainerId) {
        StringBuffer sb = new StringBuffer();
        WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(new BigInteger(workFlowContainerId));
        Map<String, Map<String, String>> beforePartMap = new HashMap<>();
        Map<String, Map<String, String>> beforeDrawMap = new HashMap<>();
        Map<String, Map<String, String>> afterPartMap = new HashMap<>();
        Map<String, Map<String, String>> afterDrawMap = new HashMap<>();
        String changeNo = "";
        if (!Objects.isNull(workFlowContainerView)) {
            if (workFlowContainerView instanceof FlowChangeIssueView) {

            } else if (workFlowContainerView instanceof FlowChangeRequestView) {
                FlowChangeRequestView flowChangeRequestView = (FlowChangeRequestView) workFlowContainerView;
                //获取变更请求对象
                ChgRequestDetailVO chgRequestDetailVO = flowChangeRequestView.getChgRequestDetailVO();
                changeNo = chgRequestDetailVO.getObjectNumber();
                List<ECLinkObjDataCommonVO> eclinkObjList = this.typlmEcAgainstDataService.batchGetAffectedObjectListByOids(Collections.singletonList(chgRequestDetailVO.getOid()), chgRequestDetailVO.getOtype());
                if (CollectionUtils.isNotEmpty(eclinkObjList)) {
                    for (ECLinkObjDataCommonVO ecLinkObjDataCommonVO : eclinkObjList) {
                        String otype = ecLinkObjDataCommonVO.getOtype();
                        BigInteger oid = ecLinkObjDataCommonVO.getOid();
                        String stage = rtChangeMapper.queryIBAValueByOidAndOtype(String.valueOf(oid), otype, "Stage");//阶段
                        String name = ecLinkObjDataCommonVO.getName();
                        String number = ecLinkObjDataCommonVO.getObjectNumber();
                        String version = ecLinkObjDataCommonVO.getVariation1() + "." + ecLinkObjDataCommonVO.getVariation2();
                        Map<String, String> tempMap = new HashMap<>();
                        if (otype.equals(TableTypeConstrant.TY_PART_OTYPE)) {
                            tempMap.put("oid", String.valueOf(oid));
                            tempMap.put("otype", otype);
                            tempMap.put("stage", stage);
                            tempMap.put("name", name);
                            tempMap.put("number", number);
                            tempMap.put("type", ecLinkObjDataCommonVO.getTypeDefName());
                            tempMap.put("version", version);
                            beforePartMap.put(number, tempMap);
                        } else if (otype.equals(TableTypeConstrant.TY_CADDOC_OTYPE)) {
                            tempMap.put("oid", String.valueOf(oid));
                            tempMap.put("otype", otype);
                            tempMap.put("name", name);
                            tempMap.put("stage", stage);
                            tempMap.put("number", number);
                            tempMap.put("type", ecLinkObjDataCommonVO.getTypeDefName());
                            tempMap.put("version", version);
                            beforeDrawMap.put(number, tempMap);
                        }
                    }
                }
            } else if (workFlowContainerView instanceof FlowChgFormView) {
                FlowChgFormView flowChgFormView = (FlowChgFormView) workFlowContainerView;
                //获取变更通告对象
                ChgFormVO chgFormVO = flowChgFormView.getChgFormVO();
                changeNo = chgFormVO.getObjectNumber();
                List<ECObjData> ecobjList = chgFormVO.getEcObjDataVOS();
                if (CollectionUtils.isNotEmpty(ecobjList)) {
                    for (ECObjData ecObjData : ecobjList) {
                        String otype = ecObjData.getOtype();
                        BigInteger oid = ecObjData.getOid();
                        String stage = rtChangeMapper.queryIBAValueByOidAndOtype(String.valueOf(oid), otype, "Stage");//阶段
                        String name = ecObjData.getName();
                        String number = ecObjData.getObjectNumber();
                        String version = ecObjData.getVariation1() + "." + ecObjData.getVariation2();
                        Map<String, String> tempMap = new HashMap<>();
                        if (otype.equals(TableTypeConstrant.TY_PART_OTYPE)) {
                            tempMap.put("oid", String.valueOf(oid));
                            tempMap.put("otype", otype);
                            tempMap.put("name", name);
                            tempMap.put("number", number);
                            tempMap.put("stage", stage);
                            tempMap.put("type", ecObjData.getTypeDefName());
                            tempMap.put("version", version);
                            beforePartMap.put(number, tempMap);
                        } else if (otype.equals(TableTypeConstrant.TY_CADDOC_OTYPE)) {
                            tempMap.put("oid", String.valueOf(oid));
                            tempMap.put("otype", otype);
                            tempMap.put("name", name);
                            tempMap.put("number", number);
                            tempMap.put("stage", stage);
                            tempMap.put("type", ecObjData.getTypeDefName());
                            tempMap.put("version", version);
                            beforeDrawMap.put(number, tempMap);
                        }
                    }
                }
                List<ECObjData> affectVOS = chgFormVO.getEcAffectVOS();
                if (CollectionUtils.isNotEmpty(affectVOS)) {
                    for (ECObjData ecObjData : affectVOS) {
                        String otype = ecObjData.getOtype();
                        BigInteger oid = ecObjData.getOid();
                        String stage = rtChangeMapper.queryIBAValueByOidAndOtype(String.valueOf(oid), otype, "Stage");//阶段
                        String name = ecObjData.getName();
                        String number = ecObjData.getObjectNumber();
                        String version = ecObjData.getVariation1() + "." + ecObjData.getVariation2();
                        Map<String, String> tempMap = new HashMap<>();
                        if (otype.equals(TableTypeConstrant.TY_PART_OTYPE)) {
                            tempMap.put("oid", String.valueOf(oid));
                            tempMap.put("otype", otype);
                            tempMap.put("name", name);
                            tempMap.put("number", number);
                            tempMap.put("stage", stage);
                            tempMap.put("type", ecObjData.getTypeDefName());
                            tempMap.put("version", version);
                            afterPartMap.put(number, tempMap);
                        } else if (otype.equals(TableTypeConstrant.TY_CADDOC_OTYPE)) {
                            tempMap.put("oid", String.valueOf(oid));
                            tempMap.put("otype", otype);
                            tempMap.put("name", name);
                            tempMap.put("number", number);
                            tempMap.put("stage", stage);
                            tempMap.put("type", ecObjData.getTypeDefName());
                            tempMap.put("version", version);
                            afterDrawMap.put(number, tempMap);
                        }
                    }
                }
            }
            List<RtChangeaffectDrawingdocumentDO> drawingdocumentDOS = new ArrayList<>();
            List<RtChangeaffectChangeobjectDO> changeobjectDOS = new ArrayList<>();
            if (StringUtils.isNotBlank(changeNo)) {
                //受影响的图纸
//                drawingdocumentDOS = this.rtChangeaffectDrawingdocumentMapper.queryByChangeNoAndPartNo(changeNo, "");
//                changeobjectDOS = this.rtChangeaffectChangeobjectMapper.queryByChangeNoAndPartNo(changeNo, "");
            }

            if (beforeDrawMap.size() > 0) {
                for (String key : beforeDrawMap.keySet()) {
                    Map<String, String> tempMap = beforeDrawMap.get(key);
                    String stage = tempMap.get("stage");
                    String number = tempMap.get("number");
                    String name = tempMap.get("name");
                    if ("S".equals(stage) || "A".equals(stage)) {
                        String msg = "图纸:" + number + "(" + name + ")的阶段为" + stage + "阶段;";
                        sb.append(msg);
                    }
                }
                if (StringUtils.isNotBlank(sb.toString())) {
                    throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("以下图纸不能走变更流程:" + sb.toString());
                }
            }
            if (afterDrawMap.size() > 0) {
                for (String key : afterDrawMap.keySet()) {
                    Map<String, String> tempMap = afterDrawMap.get(key);
                    String stage = tempMap.get("stage");
                    String number = tempMap.get("number");
                    String name = tempMap.get("name");
                    if ("S".equals(stage) || "A".equals(stage)) {
                        String msg = "图纸:" + number + "(" + name + ")的阶段为" + stage + "阶段;";
                        sb.append(msg);
                    }
                }
                if (StringUtils.isNotBlank(sb.toString())) {
                    throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("以下图纸不能走变更流程:" + sb.toString());
                }
            }
            //查询关联的图纸
            if (beforeDrawMap.size() > 0) {
                for (String key : beforeDrawMap.keySet()) {
                    Map<String, String> tempMap = beforeDrawMap.get(key);
                    BigInteger oid = new BigInteger(tempMap.get("oid"));
                    String number = tempMap.get("number");
                    List<PartDetailsVO> partdetails = this.typlmCADRelObjectService.queryCadRefPartInfo(oid);
                    if (partdetails != null) {
                        for (PartDetailsVO partDetailsVO : partdetails) {
                            if (number.contains(partDetailsVO.getObjectNumber())) {
                                if (!beforePartMap.containsKey(partDetailsVO.getNumber())) {
                                    String msg = "零部件" + partDetailsVO.getNumber() + "(" + partDetailsVO.getName() + ");";
                                    sb.append(msg);
                                }
                            }
                        }
                    }
                }
            }

            if (beforePartMap.size() > 0) {
                for (String key : beforePartMap.keySet()) {
                    Map<String, String> tempMap = beforePartMap.get(key);
                    BigInteger oid = new BigInteger(tempMap.get("oid"));
                    String otype = tempMap.get("otype");
                    String number = tempMap.get("number");
                    String type = tempMap.get("type");
                    //输出要求
                    String OutputRequirements = rtChangeMapper.queryIBAValueByOidAndOtype(String.valueOf(oid), otype, "OutputRequirements");
                    if (StringUtils.isBlank(OutputRequirements)) continue;
                    List<String> drawTypeList = new ArrayList<>();
                    if (OutputRequirements.contains("3D")) drawTypeList.add("三维数模");
                    if (OutputRequirements.contains("2D")) drawTypeList.add("二维图纸");
                    List<String> drawErrorList = new ArrayList<>();
                    for (String drawType : drawTypeList) {
                        List<DocDetails> docDetails = this.typlmPartRelObjectService.queryPartRelatedDocInfo(oid);
                        if (CollUtil.isNotEmpty(docDetails)) {
                            List<DocDetails> drawList = docDetails.stream().filter(e -> e.getCadType().contains(drawType)).collect(Collectors.toList());
                            if (CollUtil.isEmpty(drawList)) {
                                int count = 0;
                                for (DocDetails docDetail : drawList) {
                                    if (!afterDrawMap.containsKey(docDetail.getNumber())) {
                                        count++;
                                    }
                                }
                                if (drawList.size() == 0 || (drawList.size() != 0 && count == drawList.size())) {
                                    drawErrorList.add(drawType);
                                }
                            }
                        } else {
                            drawErrorList.add(drawType);
                        }
                    }
                    if (CollUtil.isNotEmpty(drawErrorList)) sb.append(type + ":" + number + "的" + String.join("/", drawErrorList) + ",");
                }
            }
            if (StringUtils.isNotBlank(sb.toString())) {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("以下对象未添加到变更对象中:" + sb.toString());
            }

            //查询关联的图纸
            if (afterDrawMap.size() > 0) {
                for (String key : afterDrawMap.keySet()) {
                    Map<String, String> tempMap = afterDrawMap.get(key);
                    BigInteger oid = new BigInteger(tempMap.get("oid"));
                    String number = tempMap.get("number");
                    List<PartDetailsVO> partdetails = this.typlmCADRelObjectService.queryCadRefPartInfo(oid);
                    if (partdetails != null) {
                        for (PartDetailsVO partDetailsVO : partdetails) {
                            if (number.contains(partDetailsVO.getObjectNumber())) {
                                if (!afterPartMap.containsKey(partDetailsVO.getNumber())) {
                                    String msg = "零部件" + partDetailsVO.getNumber() + "(" + partDetailsVO.getName() + ");";
                                    sb.append(msg);
                                }
                            }
                        }
                    }
                }
            }

            if (afterPartMap.size() > 0) {
                for (String key : afterPartMap.keySet()) {
                    Map<String, String> tempMap = afterPartMap.get(key);
                    BigInteger oid = new BigInteger(tempMap.get("oid"));
                    String otype = tempMap.get("otype");
                    String number = tempMap.get("number");
                    String type = tempMap.get("type");
                    //输出要求
                    String OutputRequirements = rtChangeMapper.queryIBAValueByOidAndOtype(String.valueOf(oid), otype, "OutputRequirements");
                    if (StringUtils.isBlank(OutputRequirements)) continue;
                    List<String> drawTypeList = new ArrayList<>();
                    if (OutputRequirements.contains("3D")) drawTypeList.add("三维数模");
                    if (OutputRequirements.contains("2D")) drawTypeList.add("二维图纸");
                    List<String> drawErrorList = new ArrayList<>();
                    for (String drawType : drawTypeList) {
                        List<DocDetails> docDetails = this.typlmPartRelObjectService.queryPartRelatedDocInfo(oid);
                        if (CollUtil.isNotEmpty(docDetails)) {
                            List<DocDetails> drawList = docDetails.stream().filter(e -> e.getCadType().contains(drawType)).collect(Collectors.toList());
                            if (CollUtil.isEmpty(drawList)) {
                                int count = 0;
                                for (DocDetails docDetail : drawList) {
                                    if (!afterDrawMap.containsKey(docDetail.getNumber())) {
                                        count++;
                                    }
                                }
                                if (drawList.size() == 0 || (drawList.size() != 0 && count == drawList.size())) {
                                    drawErrorList.add(drawType);
                                }
                            }
                        } else {
                            drawErrorList.add(drawType);
                        }
                    }
                    if (CollUtil.isNotEmpty(drawErrorList)) sb.append(type + ":" + number + "的" + String.join("/", drawErrorList) + ",");
                }
            }
            if (StringUtils.isNotBlank(sb.toString())) {
                throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("以下对象未添加到变更后对象中：" + sb.toString());
            }

            if ((workFlowContainerView instanceof WorkFlowObjectPackage)) {
                log.info("当前流程属于普通流程");
                WorkFlowObjectPackage workFlowObjectPackage = (WorkFlowObjectPackage) workFlowContainerView;
                List<FlowObject> flowObjectList = workFlowObjectPackage.getFlowObjectList();
                if (CollUtil.isNotEmpty(flowObjectList)) {
                    StringBuffer msg = new StringBuffer();
                    for (FlowObject flowObject : flowObjectList) {
                        BigInteger parentOid = flowObject.getRefObjectOid();
                        String parentNumber = flowObject.getObjectNumber();
                        String parentName = flowObject.getName();
                        String otype = flowObject.getRefObjectOtype();
                        BigInteger oid = flowObject.getRefObjectOid();
                        String stage = rtChangeMapper.queryIBAValueByOidAndOtype(String.valueOf(oid), otype, "Stage");//阶段
                        String name = flowObject.getRefObjectName();
                        String number = flowObject.getObjectNumber();
                        String version = flowObject.getRefObjectVersion();
                        Map<String, String> tempMap = new HashMap<>();
                        if (otype.equals(TableTypeConstrant.TY_PART_OTYPE)) {
                            tempMap.put("oid", String.valueOf(oid));
                            tempMap.put("otype", otype);
                            tempMap.put("name", name);
                            tempMap.put("number", number);
                            tempMap.put("stage", stage);
                            tempMap.put("version", version);
                            beforePartMap.put(number, tempMap);
                        } else if (otype.equals(TableTypeConstrant.TY_CADDOC_OTYPE)) {
                            tempMap.put("oid", String.valueOf(oid));
                            tempMap.put("otype", otype);
                            tempMap.put("name", name);
                            tempMap.put("number", number);
                            tempMap.put("stage", stage);
                            tempMap.put("version", version);
                            beforeDrawMap.put(number, tempMap);
                        }
                    }
                }
                if (beforeDrawMap.size() > 0) {
                    for (String key : beforeDrawMap.keySet()) {
                        Map<String, String> tempMap = beforeDrawMap.get(key);
                        String stage = tempMap.get("stage");
                        String number = tempMap.get("number");
                        String name = tempMap.get("name");
                        if ("B".equals(stage)) {
                            String msg = "图纸:" + number + "(" + name + ")的阶段为" + stage + "阶段;";
                            sb.append(msg);
                        }
                    }
                    if (StringUtils.isNotBlank(sb.toString())) {
                        throw RTErrorCodeEnum.COMPLETE_DRAW_ERROR.getException("以下图纸不能走发布流程:" + sb.toString());
                    }
                }
            }
        }
        return sb.toString();
    }

    /**
     * @param code
     * @param type
     * @return
     * @throws Exception
     */
    @Override
    public List<JSONObject> getProductArea(String code, String type) throws Exception {
        List<JSONObject> areaJsonList = new ArrayList<>();
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(code)) {
            List<JSONObject> patternCodeList = new ArrayList<>();
            if (type.equalsIgnoreCase("PatternCode")) {
                patternCodeList = this.rtChangeMapper.queryMaterialCode(code, "MaterialCode", RTPlmConstant.VIEW_DESIGN);
            } else if (type.equalsIgnoreCase("MaterialCode")) {
                JSONObject jsonObject = this.rtChangeMapper.queryMaterialByCodeAndType(code, "MaterialCode", RTPlmConstant.VIEW_DESIGN);
                patternCodeList.add(jsonObject);
            }
            if (patternCodeList != null && patternCodeList.size() > 0) {
                for (JSONObject obj : patternCodeList) {
                    String PARTNUMBER = obj.getString("PARTNUMBER");
                    String NAME = obj.getString("NAME");
                    List<JSONObject> parentList = new ArrayList<>();
                    queryParentPartByType(parentList, PARTNUMBER, 0);
                    if (CollUtil.isNotEmpty(parentList)) {
                        for (JSONObject parentJson : parentList) {
                            String oid = parentJson.getString("OID");
                            String ProductCode = parentJson.getString("PARTNUMBER");
                        }
                    }
                }
            }
        }
        return Collections.emptyList();
    }

    /**
     * 查询关联图文档
     *
     * @param code
     * @return
     * @throws Exception
     */
    @Override
    public List<JSONObject> getAssociationDoc(String code) throws Exception {
        List<JSONObject> resultList = new ArrayList<>();
        JSONObject json = this.rtChangeMapper.queryMaterialByCodeAndType(code, "PatternCode", RTPlmConstant.VIEW_DESIGN);
        String oid = json.getString("OID");
        String otype = json.getString("OTYPE");
        //查询关联的图纸
        List<DocDetails> oidList1 = this.typlmPartRelObjectService.queryPartRelatedDocInfo(new BigInteger(oid));
        if (oidList1 != null) {
            for (DocDetails docDetails : oidList1) {
                List<FileDataVO> filelist = docDetails.getPrimaryFileList();
                if (filelist != null) {
                    for (FileDataVO fileDataVO : filelist) {
                        String docType = docDetails.getTypeName();
                        String docNo = docDetails.getNumber();
                        String docName = docDetails.getName();
                        String fileName = fileDataVO.getFileName();
                        String docVer = docDetails.getDisplayVersion();
                        String docStatus = docDetails.getLifecycleStateName();
                        String effectiveTime = "";
                        if (StringUtils.isNotBlank(docStatus) && "已发布".equals(docStatus)) {
                            effectiveTime = docDetails.getModifyTime();
                        }
                        String creator = docDetails.getCreatorFullName();
                        String createTime = docDetails.getCreationTime();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("docType", docType);
                        jsonObject.put("docNo", docNo);
                        jsonObject.put("docName", docName);
                        jsonObject.put("fileName", fileName);
                        jsonObject.put("docVer", docVer);
                        jsonObject.put("effectiveTime", effectiveTime);
                        jsonObject.put("docStatus", docStatus);
                        jsonObject.put("creator", creator);
                        jsonObject.put("createTime", createTime);
                        jsonObject.put("oid", docDetails.getOid());
                        jsonObject.put("otype", docDetails.getOtype());
                        resultList.add(jsonObject);
                    }
                }
            }
        }
        //查询关联的参考文档
        List<DocDetails> oidList2 = this.typlmPdmPartService.getPartLinkReferenceDoc(oid);
        if (oidList2 != null) {
            for (DocDetails docDetails : oidList2) {
                String docOid = docDetails.getOid();
                String oType = docDetails.getOtype();
                IdentifierEntity entity = new IdentifierEntity(new BigInteger(docOid), oType);
                List<FileDataVO> fileListByEntity = this.fileHandleService.getFileListByEntity(entity);
                if (fileListByEntity != null) {
                    for (FileDataVO fileDataVO : fileListByEntity) {
                        String rolekey = fileDataVO.getRolekey();
                        if ("PRIMARY".equals(rolekey)) {
                            String docType = docDetails.getTypeName();
                            String docNo = docDetails.getNumber();
                            String docName = docDetails.getName();
                            String fileName = fileDataVO.getFileName();
                            String docVer = docDetails.getDisplayVersion();
                            String docStatus = docDetails.getLifecycleStateName();
                            String effectiveTime = "";
                            if (StringUtils.isNotBlank(docStatus) && "已发布".equals(docStatus)) {
                                effectiveTime = docDetails.getModifyTime();
                            }
                            String creator = docDetails.getCreatorFullName();
                            String createTime = docDetails.getCreationTime();
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("docType", docType);
                            jsonObject.put("docNo", docNo);
                            jsonObject.put("docName", docName);
                            jsonObject.put("fileName", fileName);
                            jsonObject.put("docVer", docVer);
                            jsonObject.put("effectiveTime", effectiveTime);
                            jsonObject.put("docStatus", docStatus);
                            jsonObject.put("creator", creator);
                            jsonObject.put("createTime", createTime);
                            jsonObject.put("oid", docOid);
                            jsonObject.put("otype", oType);
                            resultList.add(jsonObject);

                        }
                    }
                }
            }
        }
        //查询关联的描述文档
        List<IdentifierEntity> identifierEntityList = new ArrayList<>();
        identifierEntityList.add(new IdentifierEntity(new BigInteger(oid), otype));
        List<QueryDescribeObjVO> describeObjVOList = this.typlmPartDescribeLinkService.queryPartDescribeDoc(identifierEntityList);
        if (describeObjVOList != null) {
            for (QueryDescribeObjVO queryDescribeObjVO : describeObjVOList) {
                List<ResultEntityVO> describeObjList = queryDescribeObjVO.getDescribeObjList();
                if (describeObjList != null) {
                    for (ResultEntityVO resultEntityVO : describeObjList) {
                        BigInteger docOid = resultEntityVO.getOid();
                        String oType = resultEntityVO.getOtype();
                        IdentifierEntity entity = new IdentifierEntity(docOid, oType);
                        List<FileDataVO> fileListByEntity = this.fileHandleService.getFileListByEntity(entity);
                        if (fileListByEntity != null) {
                            for (FileDataVO fileDataVO : fileListByEntity) {
                                String rolekey = fileDataVO.getRolekey();
                                if ("PRIMARY".equals(rolekey)) {
                                    String docType = resultEntityVO.getTypeDefName();
                                    String docNo = resultEntityVO.getObjectNumber();
                                    String docName = resultEntityVO.getName();
                                    String fileName = fileDataVO.getFileName();
                                    String docVer = resultEntityVO.getMajorVersion() + "." + resultEntityVO.getMinorVersion();
                                    String docStatus = resultEntityVO.getLifecyclestagekeyName();
                                    String effectiveTime = "";
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    if (StringUtils.isNotBlank(docStatus) && "已发布".equals(docStatus)) {
                                        effectiveTime = sdf.format(resultEntityVO.getModifystamp());
                                    }
                                    String creator = resultEntityVO.getCreatorFullName();
                                    String createTime = sdf.format(resultEntityVO.getCreatestamp());
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("docType", docType);
                                    jsonObject.put("docNo", docNo);
                                    jsonObject.put("docName", docName);
                                    jsonObject.put("fileName", fileName);
                                    jsonObject.put("docVer", docVer);
                                    jsonObject.put("effectiveTime", effectiveTime);
                                    jsonObject.put("docStatus", docStatus);
                                    jsonObject.put("creator", creator);
                                    jsonObject.put("createTime", createTime);
                                    jsonObject.put("oid", docOid.toString());
                                    jsonObject.put("otype", oType);
                                    resultList.add(jsonObject);
                                }
                            }
                        }
                    }
                }
            }
        }
        return resultList;
    }

    @Override
    public List<Map<String, Object>> getOrderNo(String code, String type) {
        return Collections.emptyList();
    }

    /**
     * 影响分析页面加载数据
     *
     * @param reqMap
     * @return
     */
    @SneakyThrows
    @Override
    public JSONObject getChangeImpactAnalysis(LinkedHashMap<String, Object> reqMap) {
        JSONObject result = new JSONObject();
        if (!reqMap.isEmpty()) {
            List<String> PatternList = (List) reqMap.get("PatternCode");
            List<String> MaterialList = (List) reqMap.get("MaterialCode");
            if (CollectionUtils.isEmpty(PatternList)) {
                PatternList = new ArrayList<>();
            }
            if (CollectionUtils.isEmpty(MaterialList)) {
                MaterialList = new ArrayList<>();
            }
            String changeNo = (String) reqMap.get("changeNo");
            List<JSONObject> jsons = new ArrayList<>();

            if (CollectionUtils.isNotEmpty(PatternList)) {
                for (String PatternCode : PatternList) {
                    JSONObject tempjson = this.rtChangeMapper.queryMaterialByCodeAndType(PatternCode, "PatternCode", RTPlmConstant.VIEW_DESIGN);
                    String oid = tempjson.getString("OID");
                    String otype = tempjson.getString("OTYPE");
                    //获取关联图文档
                    List<JSONObject> DrawingDocumentList = new ArrayList<>();
                    Map<String, PartDetailsVO> map = getAffectPatternCodes(oid, otype, "PatternCode");
                    for (String key : map.keySet()) {
                        PartDetailsVO partDetailsVO = map.get(key);
                        DrawingDocumentList = getAffectDrawingDoc(DrawingDocumentList, key, partDetailsVO);
                    }
                    result.put("DrawingDocument", DrawingDocumentList);
                    //获取EBOM
                    List<JSONObject> ebomList = new ArrayList<>();
                    Map<String, Map<String, String>> tempmap = new HashMap<>();
                    ebomList = queryEBOM(ebomList, tempmap, PatternCode, "", 0, "1", "PatternCode");
                    result.put("EBOM", ebomList);
                    //获取成品BOM
                    tempmap = new HashMap<>();
                    //获取模组信息
                    queryProductBOM(result, tempmap, PatternCode, "", 0, "1", "MaterialCode", "PatternCode");

                    //获取影响分析数据
                    List<JSONObject> affectList = new ArrayList<>();
                    affectList = queryAffectList(affectList, PatternCode, "PatternCode");
                    result.put("changeObject", affectList);

                    //获取指定信息
                    List<JSONObject> appointtList = new ArrayList<>();
                    appointtList = queryAppointtListList(appointtList, PatternCode, "MaterialCode");
                    result.put("appoint", appointtList);

                    //获取认证信息
                    List<JSONObject> accreditationList = new ArrayList<>();
                    accreditationList = queryAccreditationList(accreditationList, PatternCode, "PatternCode");
                    result.put("authentication", accreditationList);

                    List<JSONObject> list = this.rtChangeMapper.queryMaterialCode(PatternCode, "MaterialCode", RTPlmConstant.VIEW_DESIGN);
                }
            }
            if (CollectionUtils.isNotEmpty(MaterialList)) {
                for (String MaterialCode : MaterialList) {
                    String parttype = "";
                    String PatternCode = "";
                    if (MaterialCode.length() == 18) {
                        //编码长度18是物料码
                        parttype = "MaterialCode";
                        PatternCode = MaterialCode.substring(0, 13);
                    } else {
                        //编码长度15是标准件
                        parttype = "Standard";
                        PatternCode = MaterialCode;
                    }
                    JSONObject tempjson = this.rtChangeMapper.queryMaterialByCodeAndType(MaterialCode, parttype, RTPlmConstant.VIEW_DESIGN);
                    if (tempjson == null) {
                        continue;
                    }
                    String oid = tempjson.getString("OID");
                    String otype = tempjson.getString("OTYPE");
                    //获取关联图文档
                    List<JSONObject> DrawingDocumentList = new ArrayList<>();
                    Map<String, PartDetailsVO> map = getAffectPatternCodes(oid, otype, "MaterialCode");
                    for (String key : map.keySet()) {
                        PartDetailsVO partDetailsVO = map.get(key);
                        DrawingDocumentList = getAffectDrawingDoc(DrawingDocumentList, key, partDetailsVO);
                    }
                    result.put("DrawingDocument", DrawingDocumentList);
                    //获取EBOM
                    List<JSONObject> ebomList = new ArrayList<>();
                    Map<String, Map<String, String>> tempmap = new HashMap<>();
//                    ebomList = queryEBOM(ebomList, tempmap, PatternCode, "", 0, "1", "PatternCode");
//                    result.put("EBOM", ebomList);
                    //获取成品BOM
                    //获取模组信息
                    tempmap = new HashMap<>();
                    queryProductBOM(result, tempmap, MaterialCode, "", 0, "1", "MaterialCode", "MaterialCode");
                    //获取影响分析数据
                    List<JSONObject> affectList = new ArrayList<>();
                    affectList = queryAffectList(affectList, MaterialCode, "MaterialCode");
                    result.put("changeObject", affectList);

                    //获取指定信息
                    List<JSONObject> appointtList = new ArrayList<>();
                    appointtList = queryAppointtListList(appointtList, MaterialCode, "MaterialCode");
                    result.put("appoint", appointtList);

                    //获取认证信息
                    List<JSONObject> accreditationList = new ArrayList<>();
                    accreditationList = queryAccreditationList(accreditationList, MaterialCode, "MaterialCode");
                    result.put("authentication", accreditationList);


                    List<JSONObject> list = this.rtChangeMapper.queryMaterialCode(MaterialCode, "MaterialCode", RTPlmConstant.VIEW_DESIGN);
                }
            }
        }
        return result;
    }

    /**
     * 影响分析页面保存逻辑
     *
     * @param map
     * @return
     */
    @Transactional
    @Override
    public String saveChangeImpactAnalysis(LinkedHashMap<String, Object> map) throws Exception {
        UserDO user = TyAccountContext.getUser();
        String changeNo = map.get("changeNo").toString();
        String partnumber = map.get("partNumber").toString();
        if (StringUtils.isNotBlank(changeNo) && StringUtils.isNotBlank(partnumber)) {
            List<Map<String, Object>> changeObjects = (List<Map<String, Object>>) map.get("changeObject");
            List<Map<String, Object>> appoints = (List<Map<String, Object>>) map.get("appoint");
            List<Map<String, Object>> EBOMs = (List<Map<String, Object>>) map.get("EBOM");
            List<Map<String, Object>> FinishedBOMs = (List<Map<String, Object>>) map.get("FinishedBOM");
            List<Map<String, Object>> DrawingDocuments = (List<Map<String, Object>>) map.get("DrawingDocument");
            List<Map<String, Object>> inventorys = (List<Map<String, Object>>) map.get("inventory");
            List<Map<String, Object>> modules = (List<Map<String, Object>>) map.get("module");
            List<Map<String, Object>> authentications = (List<Map<String, Object>>) map.get("authentication");
            if (CollectionUtils.isNotEmpty(changeObjects)) {
                // 1. 保留null值并禁用循环引用检测
                String jsonObject = JSON.toJSONString(changeObjects, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                List<RtChangeaffectChangeobjectDO> changeobjectDOS = JSON.parseArray(jsonObject, RtChangeaffectChangeobjectDO.class);
                for (RtChangeaffectChangeobjectDO changeobjectDO : changeobjectDOS) {
                    changeobjectDO.setCreateBy(user.getDisplayName());
                    changeobjectDO.setChangeno(changeNo);
                    changeobjectDO.setPartnumber(partnumber);
                }
                long count = rtChangeaffectChangeobjectMapper.count(new RtChangeaffectChangeobjectDO(changeNo, partnumber));
                if (count > 0) {
                    rtChangeaffectChangeobjectMapper.deleteById(changeNo, partnumber);
                }
                int i = rtChangeaffectChangeobjectMapper.insertBatch(changeobjectDOS);

            }
            if (appoints != null && appoints.size() > 0) {
                String jsonObject = JSON.toJSONString(appoints, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                List<RtChangeaffectAppointDO> appointDOS = JSON.parseArray(jsonObject, RtChangeaffectAppointDO.class);
                for (RtChangeaffectAppointDO appointDO : appointDOS) {
                    appointDO.setCreateBy(user.getDisplayName());
                    appointDO.setChangeno(changeNo);
                    appointDO.setPartnumber(partnumber);
                    appointDO.setType("研发");
                }
                long count = rtChangeaffectAppointMapper.count(new RtChangeaffectAppointDO(changeNo, partnumber, "研发"));
                if (count > 0) {
                    rtChangeaffectAppointMapper.deleteById(changeNo, partnumber, "研发");
                }
                int i = rtChangeaffectAppointMapper.insertBatch(appointDOS);
            }
            if (authentications != null && authentications.size() > 0) {
                String jsonObject = JSON.toJSONString(authentications, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                List<RtChangeaffectAuthenticationDO> authenticationDOS = JSON.parseArray(jsonObject, RtChangeaffectAuthenticationDO.class);
                for (RtChangeaffectAuthenticationDO authenticationDO : authenticationDOS) {
                    authenticationDO.setCreateBy(user.getDisplayName());
                    authenticationDO.setChangeno(changeNo);
                    authenticationDO.setPartnumber(partnumber);
                }
                long count = rtChangeaffectAuthenticationMapper.count(new RtChangeaffectAuthenticationDO(changeNo, partnumber));
                if (count > 0) {
                    rtChangeaffectAuthenticationMapper.deleteById(changeNo, partnumber);
                }
                int i = rtChangeaffectAuthenticationMapper.insertBatch(authenticationDOS);
            }

            List<AffectedObjectDTO> affectobjectList = new ArrayList<>();
            List<ECObjDTO> entityList = new ArrayList<>();
            if (EBOMs != null && EBOMs.size() > 0) {
                String jsonObject = JSON.toJSONString(EBOMs, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                List<RtChangeaffectEbomDO> ebomDOS = JSON.parseArray(jsonObject, RtChangeaffectEbomDO.class);
                for (RtChangeaffectEbomDO ebomDO : ebomDOS) {
                    ebomDO.setCreateBy(user.getDisplayName());
                    ebomDO.setChangeno(changeNo);
                    ebomDO.setPartnumber(partnumber);
                    //收集变更前对象
                    ECObjDTO entity = new ECObjDTO();
                    entity.setOid(new BigInteger(ebomDO.getObjectid()));
                    entity.setOtype(ebomDO.getObjecttype());
                    entityList.add(entity);
                    //收集受影响的对象
                    AffectedObjectDTO affectedObjectDTO = new AffectedObjectDTO(new BigInteger(ebomDO.getObjectid()), ebomDO.getObjecttype(), "");
                    affectobjectList.add(affectedObjectDTO);
                }
                long count = rtChangeaffectEbomMapper.count(new RtChangeaffectEbomDO(changeNo, partnumber));
                if (count > 0) {
                    rtChangeaffectEbomMapper.deleteById(changeNo, partnumber);
                }
                int i = rtChangeaffectEbomMapper.insertBatch(ebomDOS);
            }

            if (FinishedBOMs != null && FinishedBOMs.size() > 0) {
                String jsonObject = JSON.toJSONString(FinishedBOMs, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                List<RtChangeaffectFinishedbomDO> finishedbomDOS = JSON.parseArray(jsonObject, RtChangeaffectFinishedbomDO.class);
                for (RtChangeaffectFinishedbomDO finishedbomDO : finishedbomDOS) {
                    finishedbomDO.setCreateBy(user.getDisplayName());
                    finishedbomDO.setChangeno(changeNo);
                    finishedbomDO.setPartnumber(partnumber);
                    //收集变更前对象
                    ECObjDTO entity = new ECObjDTO();
                    entity.setOid(new BigInteger(finishedbomDO.getObjectid()));
                    entity.setOtype(finishedbomDO.getObjecttype());
                    entityList.add(entity);
                    //收集受影响的对象
                    AffectedObjectDTO affectedObjectDTO = new AffectedObjectDTO(new BigInteger(finishedbomDO.getObjectid()), finishedbomDO.getObjecttype(), "");
                    affectobjectList.add(affectedObjectDTO);
                }
                long count = rtChangeaffectFinishedbomMapper.count(new RtChangeaffectFinishedbomDO(changeNo, partnumber));
                if (count > 0) {
                    rtChangeaffectFinishedbomMapper.deleteById(changeNo, partnumber);
                }
                int i = rtChangeaffectFinishedbomMapper.insertBatch(finishedbomDOS);
            }

            if (DrawingDocuments != null && DrawingDocuments.size() > 0) {
                String jsonObject = JSON.toJSONString(DrawingDocuments, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                List<RtChangeaffectDrawingdocumentDO> drawingdocumentDOS = JSON.parseArray(jsonObject, RtChangeaffectDrawingdocumentDO.class);
                for (RtChangeaffectDrawingdocumentDO drawingdocumentDO : drawingdocumentDOS) {
                    drawingdocumentDO.setCreateBy(user.getDisplayName());
                    drawingdocumentDO.setChangeno(changeNo);
                    drawingdocumentDO.setPartnumber(partnumber);
                    //收集变更前对象
                    ECObjDTO entity = new ECObjDTO();
                    entity.setOid(new BigInteger(drawingdocumentDO.getObjectid()));
                    entity.setOtype(drawingdocumentDO.getObjecttype());
                    entityList.add(entity);
                    //收集受影响的对象
                    AffectedObjectDTO affectedObjectDTO = new AffectedObjectDTO(new BigInteger(drawingdocumentDO.getObjectid()), drawingdocumentDO.getObjecttype(), "");
                    affectobjectList.add(affectedObjectDTO);
                }
                long count = rtChangeaffectDrawingdocumentMapper.count(new RtChangeaffectDrawingdocumentDO(changeNo, partnumber));
                if (count > 0) {
                    rtChangeaffectDrawingdocumentMapper.deleteById(changeNo, partnumber);
                }
                int i = rtChangeaffectDrawingdocumentMapper.insertBatch(drawingdocumentDOS);
            }

            if (inventorys != null && inventorys.size() > 0) {
                String jsonObject = JSON.toJSONString(inventorys, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                List<RtChangeaffectInventoryDO> inventoryDOS = JSON.parseArray(jsonObject, RtChangeaffectInventoryDO.class);
                for (RtChangeaffectInventoryDO inventoryDO : inventoryDOS) {
                    inventoryDO.setCreateBy(user.getDisplayName());
                    inventoryDO.setChangeno(changeNo);
                    inventoryDO.setPartnumber(partnumber);
                }
                long count = rtChangeaffectInventoryMapper.count(new RtChangeaffectInventoryDO(changeNo, partnumber));
                if (count > 0) {
                    rtChangeaffectInventoryMapper.deleteById(changeNo, partnumber);
                }
                int i = rtChangeaffectInventoryMapper.insertBatch(inventoryDOS);
            }

            if (modules != null && modules.size() > 0) {
                String jsonObject = JSON.toJSONString(modules, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                List<RtChangeaffectModuleDO> moduleDOS = JSON.parseArray(jsonObject, RtChangeaffectModuleDO.class);
                for (RtChangeaffectModuleDO moduleDO : moduleDOS) {
                    moduleDO.setCreateBy(user.getDisplayName());
                    moduleDO.setChangeno(changeNo);
                    moduleDO.setPartnumber(partnumber);
                }
                long count = rtChangeaffectModuleMapper.count(new RtChangeaffectModuleDO(changeNo, partnumber));
                if (count > 0) {
                    rtChangeaffectModuleMapper.deleteById(changeNo, partnumber);
                }
                int i = rtChangeaffectModuleMapper.insertBatch(moduleDOS);
            }
        }
        return "保存成功";
    }

    /**
     * 关联变更对象页面加载逻辑
     *
     * @param changeNo
     * @param partNo
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject getRelateChangeDetail(String changeNo, String partNo) throws Exception {
        JSONObject result = new JSONObject();
        //获取关联图文档
        List<RtChangeaffectDrawingdocumentDO> DrawingDocumentList = rtChangeaffectDrawingdocumentMapper.queryByChangeNoAndPartNo(changeNo, partNo);
        result.put("DrawingDocument", DrawingDocumentList);
        //获取EBOM
        List<RtChangeaffectEbomDO> ebomList = rtChangeaffectEbomMapper.queryByChangeNoAndPartNo(changeNo, partNo);
        result.put("EBOM", ebomList);
        //获取成品BOM
        List<RtChangeaffectFinishedbomDO> productList = rtChangeaffectFinishedbomMapper.queryByChangeNoAndPartNo(changeNo, partNo);
        result.put("FinishedBOM", productList);
        //获取影响分析数据
        List<RtChangeaffectChangeobjectDO> affectList = rtChangeaffectChangeobjectMapper.queryByChangeNoAndPartNo(changeNo, partNo);
        result.put("changeObject", affectList);

        //获取指定信息
        List<RtChangeaffectAppointDO> appointtList = rtChangeaffectAppointMapper.queryByChangeNoAndPartNo(changeNo, partNo, "研发");
        result.put("appoint", appointtList);

        //获取认证信息
        List<RtChangeaffectAuthenticationDO> accreditationList = rtChangeaffectAuthenticationMapper.queryByChangeNoAndPartNo(changeNo, partNo);
        result.put("authentication", accreditationList);

        //获取库存信息
        List<RtChangeaffectInventoryDO> inventorDOS = rtChangeaffectInventoryMapper.queryByChangeNoAndPartNo(changeNo, partNo);
        result.put("inventory", inventorDOS);

        //获取模组信息
        List<RtChangeaffectModuleDO> moduleDOS = rtChangeaffectModuleMapper.queryByChangeNoAndPartNo(changeNo, partNo);
        result.put("module", moduleDOS);

        return result;
    }

    /**
     * 查询订单项次
     *
     * @param partNo
     * @return
     * @throws Exception
     */
    @Override
    public List<JSONObject> getOrderInquiry(String partNo) throws Exception {
        List<JSONObject> result = new ArrayList<>();
        if (StringUtils.isNotBlank(partNo)) {
            String partName = "";
            List<PartDetailsVO> productCodes = new ArrayList<>();
            List<JSONObject> materialCodes = this.rtChangeMapper.queryMaterialCode(partNo, "MaterialCode", RTPlmConstant.VIEW_DESIGN);
            for (JSONObject materialCodeJson : materialCodes) {
                String materialCode = materialCodeJson.getString("PARTNUMBER");
                partName = materialCodeJson.getString("NAME");
                productCodes = queryParentProductCodePart(productCodes, materialCode, 0);
            }
            String productCode = "";
            for (PartDetailsVO detailsVO : productCodes) {
                //根据物料码查询订单号、项次 CRM
                String code = detailsVO.getObjectNumber();
                if (StringUtils.isNotBlank(code)) {
                    if (StringUtils.isNotBlank(productCode)) {
                        productCode += ",";
                    }
                    productCode += code;
                }
            }
            if (StringUtils.isNotBlank(productCode)) {
                JSONObject json = new JSONObject();
                json.put("MaterialCode", productCode);
                json.put("OrderType", "");
                json.put("ItemType", "");
                json.put("Factory", "");
                String body = json.toString();
                String orderStr = this.commonService.sendPostRequest(crmOrderListUrl, crmOrderListUsername, crmorderListPassword, body);
                if (StringUtils.isBlank(orderStr)) {
                    throw new Exception("返回参数为空！");
                }
                JSONObject orderJson = JSON.parseObject(orderStr);
                JSONArray array = orderJson.getJSONArray("data");
                for (int i = 0; i < array.size(); i++) {
                    JSONObject tempJson = array.getJSONObject(i);
                    String ProductCode = tempJson.getString("MATNR");//成品码
                    String OrderNo = tempJson.getString("VBELN");//订单号
                    String ITEM = tempJson.getString("POSNR");//项次
                    String model = tempJson.getString("ZKHJX");//机型
                    String OrderReportingStatus = getOrderStatus(OrderNo, ITEM);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("OrderNo", OrderNo);
                    jsonObject.put("ITEM", ITEM);
                    jsonObject.put("ProductCode", ProductCode);
                    jsonObject.put("OrderReportingStatus", OrderReportingStatus);
                    jsonObject.put("PatternCode", partNo);
                    jsonObject.put("DrawingName", partName);
                    jsonObject.put("model", model);
                    jsonObject.put("remark", "");
                    result.add(jsonObject);
                }
            }
        }
        return result;
    }

    public String getOrderStatus(String OrderNo, String ITEM) throws Exception {
        StringBuffer result = new StringBuffer();
        if (StringUtils.isNotBlank(OrderNo) && StringUtils.isNotBlank(ITEM)) {
            String newOrderNo = "";
            if (OrderNo.length() < 10) {
                for (int i = 0; i < 10 - OrderNo.length(); i++) {
                    newOrderNo += "0";
                }
                newOrderNo = newOrderNo + OrderNo;
            } else {
                newOrderNo = OrderNo;
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("VBELN", newOrderNo + "-" + ITEM);
            JSONArray array1 = new JSONArray();
            array1.add(jsonObject);
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("item", array1);
            JSONObject jsonObject3 = new JSONObject();
            jsonObject3.put("IT_VBELN", jsonObject2);
            String body = jsonObject3.toString();
            //根据订单号项次查询订单状态 SAP,
            String orderStatus = this.commonService.sendPostRequest(sapOrderListUrl, sapOrderListUsername, saporderListPassword, body);
            JSONObject orderStatusJson = JSON.parseObject(orderStatus);
            if (orderStatusJson.containsKey("ET_TAB")) {
                JSONObject tabJson = orderStatusJson.getJSONObject("ET_TAB");
                if (tabJson.containsKey("item")) {
                    JSONArray items = tabJson.getJSONArray("item");
                    for (int i = 0; i < items.size(); i++) {
                        JSONObject itemJson = items.getJSONObject(i);
                        String status = itemJson.getString("TEXT_LINE");
                        result.append(status);
                    }
                }
            }
        }
        return result.toString();
    }

    /**
     * 查询所有受影响的BOM
     *
     * @param partNo
     * @param type
     * @return
     * @throws Exception
     */
    @Override
    public List<JSONObject> queryAllAffectBOM(String partNo, String type) throws Exception {
        List<JSONObject> result = new ArrayList<>();
        if (StringUtils.isNotBlank(partNo) && StringUtils.isNotBlank(type)) {
            List<JSONObject> materiallist = new ArrayList<>();
            if ("MaterialCode".equals(type)) {
                JSONObject json = this.rtChangeMapper.queryMaterialByCodeAndType(partNo, type, RTPlmConstant.VIEW_DESIGN);
                materiallist.add(json);
            } else if ("PatternCode".equals(type)) {
                materiallist = this.rtChangeMapper.queryMaterialCode(partNo, "MaterialCode", RTPlmConstant.VIEW_DESIGN);
                JSONObject json = this.rtChangeMapper.queryMaterialByCodeAndType(partNo, type, RTPlmConstant.VIEW_DESIGN);
                if (json != null) {
                    materiallist.add(json);
                }
            }
            List<JSONObject> list = new ArrayList<>();
            if (materiallist != null && materiallist.size() > 0) {
                for (JSONObject item : materiallist) {
                    String code = item.getString("PARTNUMBER");
                    list = queryParentProductCodeAndEBOMPart(list, code, "", "", 0, "", "", "");
                }
            }
            if (list != null && list.size() > 0) {
                for (JSONObject json : list) {
                    PartDetailsVO detailsVO = json.getObject("topParent", PartDetailsVO.class);
                    String firstParent = json.getObject("firstParent", String.class);
                    JSONObject tempJson = new JSONObject();
                    tempJson.put("firstParent", firstParent);
                    tempJson.put("objectid", detailsVO.getOid());
                    tempJson.put("objecttype", detailsVO.getOtype());
                    tempJson.put("objectversion", detailsVO.getVersion() + "." + detailsVO.getIteration());
                    tempJson.put("bomType", detailsVO.getTypeName());
                    tempJson.put("code", detailsVO.getObjectNumber());
                    String CustomerCode = rtChangeMapper.queryIBAValue(detailsVO.getOid(), "CustomerCode");
                    String devCode = rtChangeMapper.queryIBAValue(detailsVO.getOid(), "devCode");
                    String productType = rtChangeMapper.queryIBAValue(detailsVO.getOid(), "productType");
                    String V2Model = rtChangeMapper.queryIBAValue(detailsVO.getOid(), "V2Model");
                    String isRestructure = rtChangeMapper.queryIBAValue(detailsVO.getOid(), "reform");
                    tempJson.put("CustomerCode", StringUtils.isEmpty(CustomerCode) ? "" : CustomerCode);
                    tempJson.put("devCode", StringUtils.isEmpty(devCode) ? "" : devCode);
                    tempJson.put("productType", StringUtils.isEmpty(productType) ? "" : productType);
                    tempJson.put("V2Model", StringUtils.isEmpty(V2Model) ? "" : V2Model);
                    tempJson.put("isRestructure", StringUtils.isEmpty(isRestructure) ? "" : isRestructure);
                    tempJson.put("error", "");
                    result.add(tempJson);
                }
            }
        }
        return result;
    }

    /**
     * 保存受影响的BOM
     *
     * @param map
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public String saveChangeImpactBOM(LinkedHashMap<String, Object> map) throws Exception {
        UserDO user = TyAccountContext.getUser();
        String changeNo = map.get("changeNo").toString();
        String partnumber = map.get("partNumber").toString();
        String type = map.get("type").toString();
        if (map != null && StringUtils.isNotBlank(changeNo) && StringUtils.isNotBlank(partnumber)) {
            List<ECObjDTO> entityList = new ArrayList<>();
            List<Map<String, Object>> affectBOMs = (List<Map<String, Object>>) map.get("affectBOM");
            if (affectBOMs != null && affectBOMs.size() > 0) {
                String jsonObject = JSON.toJSONString(affectBOMs, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
                List<RtChangeaffectAssociatedbomDO> moduleDOS = JSON.parseArray(jsonObject, RtChangeaffectAssociatedbomDO.class);
                for (RtChangeaffectAssociatedbomDO associatedbomDO : moduleDOS) {
                    associatedbomDO.setCreateBy(user.getDisplayName());
                    associatedbomDO.setChangeno(changeNo);
                    associatedbomDO.setPartnumber(partnumber);
                    associatedbomDO.setParttype(type);
                    long count = this.rtChangeaffectAssociatedbomMapper.count(new RtChangeaffectAssociatedbomDO(changeNo, partnumber, associatedbomDO.getCode()));
                    if (count > 0) {
                        this.rtChangeaffectAssociatedbomMapper.deleteById(changeNo, partnumber, associatedbomDO.getCode());
                    }
                }
                this.rtChangeaffectAssociatedbomMapper.insertBatch(moduleDOS);
            }
        }
        return "保存成功";
    }

    /**
     * 加载保存的受影响BOM
     *
     * @param changeNo
     * @param partNo
     * @return
     */
    @Override
    public List<RtChangeaffectAssociatedbomDO> querySaveAffectBOM(String changeNo, String partNo, String segmNum, String partType, String changeStyle) {
        RtChangeaffectAssociatedbomDO queryDO = new RtChangeaffectAssociatedbomDO();
        queryDO.setChangeno(changeNo);
        queryDO.setPartnumber(partNo);
        queryDO.setParttype(partType);
        queryDO.setSegmNum(segmNum);
        List<RtChangeaffectAssociatedbomDO> associatedBOMDOList = this.rtChangeaffectAssociatedbomMapper.queryByAssociatedbomDO(queryDO);
        return associatedBOMDOList;
    }

    /**
     * 同步关联对象
     *
     * @param map
     * @return
     */
    @Override
    public String synchronousAssociationObj(LinkedHashMap<String, Object> map) {
        if (map != null) {
            List<ECObjDTO> changeAfterList = new ArrayList<>();
            List<ECObjDTO> entityList = new ArrayList<>();
            String changeNo = map.get("changeNo").toString();
            List<Map<String, Object>> changeObjects = (List<Map<String, Object>>) map.get("changeObject");
            if (changeNo.startsWith("RTTJST")) {
                //更改通告
                ChgNoticeVO chgNoticeVO = this.typlmChgNoticeQueryService.queryECOByNumber(changeNo);
                //变更前对象
                List<CommonIteratorVO> commonIteratorVOList = new ArrayList<>();
                UserDO user = TyAccountContext.getUser();
                ECAddChangeObjectDTO addChangeObjectDTO = new ECAddChangeObjectDTO();
                addChangeObjectDTO.setEntity(new IdentifierEntity(chgNoticeVO.getOid(), chgNoticeVO.getOtype()));
                addChangeObjectDTO.setBefore(true);
                //变更后对象
                ECAddChangeObjectDTO addChangeAfterObjectDTO = new ECAddChangeObjectDTO();
                addChangeAfterObjectDTO.setEntity(new IdentifierEntity(chgNoticeVO.getOid(), chgNoticeVO.getOtype()));
                if (chgNoticeVO != null && changeObjects.size() > 0) {
                    for (Map<String, Object> changeObject : changeObjects) {
                        String beforeChangeNo = changeObject.get("beforeChangeNo").toString();
                        String afterChangeNo = changeObject.get("afterChangeNo").toString();
                        String type = changeObject.get("type").toString();
                        if ("图号升级".equals(type)) {
                            JSONObject beforeChangeNoJson = this.rtChangeMapper.queryLatestMaterialByCode(beforeChangeNo, RTPlmConstant.VIEW_DESIGN);
                            if (beforeChangeNoJson != null) {
                                String id = beforeChangeNoJson.getString("OID");
                                String otype = beforeChangeNoJson.getString("OTYPE");
                                ECObjDTO ecObjDTO = new ECObjDTO();
                                ecObjDTO.setOid(new BigInteger(id));
                                ecObjDTO.setOtype(otype);
                                ecObjDTO.setIdentifierRef(new IdentifierEntity(new BigInteger(id), otype));
                                entityList.add(ecObjDTO);
                            }
                            JSONObject afterChangeNoJson = this.rtChangeMapper.queryLatestMaterialByCode(afterChangeNo, RTPlmConstant.VIEW_DESIGN);
                            if (afterChangeNoJson != null) {
                                String id = afterChangeNoJson.getString("OID");
                                String otype = afterChangeNoJson.getString("OTYPE");
                                ECObjDTO ecObjDTO = new ECObjDTO();
                                ecObjDTO.setOid(new BigInteger(id));
                                ecObjDTO.setOtype(otype);
                                ecObjDTO.setIdentifierRef(new IdentifierEntity(new BigInteger(id), otype));
                                changeAfterList.add(ecObjDTO);
                            }
                        } else if ("图纸升版".equals(type)) {
                            JSONObject beforeChangeNoJson = this.rtChangeMapper.querySecLatestMaterialByCode(beforeChangeNo, RTPlmConstant.VIEW_DESIGN);
                            if (beforeChangeNoJson != null) {
                                String id = beforeChangeNoJson.getString("OID");
                                String otype = beforeChangeNoJson.getString("OTYPE");
                                ECObjDTO ecObjDTO = new ECObjDTO();
                                ecObjDTO.setOid(new BigInteger(id));
                                ecObjDTO.setOtype(otype);
                                ecObjDTO.setIdentifierRef(new IdentifierEntity(new BigInteger(id), otype));
                                entityList.add(ecObjDTO);
                            }
                            JSONObject afterChangeNoJson = this.rtChangeMapper.queryLatestMaterialByCode(beforeChangeNo, RTPlmConstant.VIEW_DESIGN);
                            if (afterChangeNoJson != null) {
                                String id = afterChangeNoJson.getString("OID");
                                String otype = afterChangeNoJson.getString("OTYPE");
                                ECObjDTO ecObjDTO = new ECObjDTO();
                                ecObjDTO.setOid(new BigInteger(id));
                                ecObjDTO.setOtype(otype);
                                ecObjDTO.setIdentifierRef(new IdentifierEntity(new BigInteger(id), otype));
                                changeAfterList.add(ecObjDTO);
                            }
                        } else if ("增加".equals(type)) {
                            JSONObject afterChangeNoJson = this.rtChangeMapper.queryLatestMaterialByCode(afterChangeNo, RTPlmConstant.VIEW_DESIGN);
                            if (afterChangeNoJson != null) {
                                String id = afterChangeNoJson.getString("OID");
                                String otype = afterChangeNoJson.getString("OTYPE");
                                ECObjDTO ecObjDTO = new ECObjDTO();
                                ecObjDTO.setOid(new BigInteger(id));
                                ecObjDTO.setOtype(otype);
                                ecObjDTO.setIdentifierRef(new IdentifierEntity(new BigInteger(id), otype));
                                changeAfterList.add(ecObjDTO);
                            }
                        } else if ("删除".equals(type)) {
                            JSONObject beforeChangeNoJson = this.rtChangeMapper.querySecLatestMaterialByCode(beforeChangeNo, RTPlmConstant.VIEW_DESIGN);
                            if (beforeChangeNoJson != null) {
                                String id = beforeChangeNoJson.getString("OID");
                                String otype = beforeChangeNoJson.getString("OTYPE");
                                ECObjDTO ecObjDTO = new ECObjDTO();
                                ecObjDTO.setOid(new BigInteger(id));
                                ecObjDTO.setOtype(otype);
                                ecObjDTO.setIdentifierRef(new IdentifierEntity(new BigInteger(id), otype));
                                entityList.add(ecObjDTO);
                            }
                        } else if ("替换".equals(type) || "修改".equals(type)) {
                            JSONObject beforeChangeNoJson = this.rtChangeMapper.queryLatestMaterialByCode(beforeChangeNo, RTPlmConstant.VIEW_DESIGN);
                            if (beforeChangeNoJson != null) {
                                String id = beforeChangeNoJson.getString("OID");
                                String otype = beforeChangeNoJson.getString("OTYPE");
                                ECObjDTO ecObjDTO = new ECObjDTO();
                                ecObjDTO.setOid(new BigInteger(id));
                                ecObjDTO.setOtype(otype);
                                ecObjDTO.setIdentifierRef(new IdentifierEntity(new BigInteger(id), otype));
                                entityList.add(ecObjDTO);
                            }
                            JSONObject afterChangeNoJson = this.rtChangeMapper.queryLatestMaterialByCode(afterChangeNo, RTPlmConstant.VIEW_DESIGN);
                            if (afterChangeNoJson != null) {
                                String id = afterChangeNoJson.getString("OID");
                                String otype = afterChangeNoJson.getString("OTYPE");
                                ECObjDTO ecObjDTO = new ECObjDTO();
                                ecObjDTO.setOid(new BigInteger(id));
                                ecObjDTO.setOtype(otype);
                                ecObjDTO.setIdentifierRef(new IdentifierEntity(new BigInteger(id), otype));
                                changeAfterList.add(ecObjDTO);
                            }
                        }
                    }
                    //批量添加变更前对象
                    addChangeObjectDTO.setEntityList(entityList);
                    List<ECObjDataVO> ecObjDataVOS = this.typlmEngineeringChangeService.addBeforeChangeObjectWithStrategy(addChangeObjectDTO);
                    //批量添加变更后对象
                    addChangeAfterObjectDTO.setEntityList(changeAfterList);
                    addChangeAfterObjectDTO.setOirAllObjList(new ArrayList<>());
                    addChangeAfterObjectDTO.setRootList(new ArrayList<>());
                    EcAfterAddReturnDTO returnDTO = this.typlmEngineeringChangeService.addAfterChangeObject(addChangeAfterObjectDTO);
                }
            } else if (changeNo.startsWith("RTTJZQ")) {
                //更改请求
                ChgRequestVO requestVO = this.changeRequestAdapter.getEcrDetailByNumber(changeNo);
                IdentifierEntity entity = new IdentifierEntity(requestVO.getOid(), requestVO.getOtype());
                List<AffectedObjectDTO> affectobjectList = new ArrayList<>();
                if (requestVO != null && CollectionUtils.isNotEmpty(changeObjects)) {
                    for (Map<String, Object> changeObject : changeObjects) {
                        String beforeChangeNo = changeObject.get("beforeChangeNo").toString();
                        String afterChangeNo = changeObject.get("afterChangeNo").toString();
                        if (StringUtils.isNotBlank(beforeChangeNo)) {
                            JSONObject beforeChangeNoJson = this.rtChangeMapper.queryLatestMaterialByCode(beforeChangeNo, RTPlmConstant.VIEW_DESIGN);
                            if (beforeChangeNoJson != null) {
                                String id = beforeChangeNoJson.getString("OID");
                                String otype = beforeChangeNoJson.getString("OTYPE");
                                AffectedObjectDTO affectedObjectDTO = new AffectedObjectDTO(new BigInteger(id), otype, "");
                                affectobjectList.add(affectedObjectDTO);
                            }
                        }
                    }
                    List<BigInteger> oidList = this.typlmEcAgainstDataService.batchCreateAffectedLinkList(entity, affectobjectList);
                }
            }
        }
        return "";
    }

    /**
     * 机型收集
     *
     * @param changeNo
     * @return
     */
    @Override
    public JSONObject collectModels(String changeNo) {
        JSONObject jsonObject = new JSONObject();
        if (StringUtils.isNotBlank(changeNo)) {
            //获取影响分析数据
            Map<String, String> enmumap = this.typlmEnumerationService.getEnabledEnumItemsMap(Collections.singletonList("relatedModels")).get("relatedModels");
            StringBuffer sb = new StringBuffer();
            List<RtChangeaffectChangeobjectDO> affectList = rtChangeaffectChangeobjectMapper.queryByChangeNoAndPartNo(changeNo, "");
            for (RtChangeaffectChangeobjectDO changeaffectChangeobjectDO : affectList) {
                String productType = changeaffectChangeobjectDO.getDevcode();
                if (StringUtils.isNotBlank(productType)) {
                    if (StringUtils.isNotBlank(sb.toString())) {
                        sb.append(",");
                    }
                    sb.append(productType);
                }
            }
            if (sb.length() > 0) {
                String[] models = sb.toString().split(",");
                for (String model : models) {
                    if (!jsonObject.containsKey(model)) {
                        String user = enmumap.get(model);
                        if (StringUtils.isNotBlank(user)) {
                            jsonObject.put(model, user);
                        }
                    }
                }
            }
        }
        return jsonObject;
    }

    /**
     * 查询开发令和机型
     *
     * @param devCode 开发令
     * @return
     */
    @Override
    public List<JSONObject> getDevCodeAndModel(String devCode) {
        List<JSONObject> result = new ArrayList<>();
        List<PartDO> list = this.rtChangeMapper.queryPartByType("ProductSpectrum");
        for (PartDO partDO : list) {
            BigInteger oid = partDO.getOid();
            String productType = this.rtChangeMapper.queryIBAValue(String.valueOf(oid), "productType");
            String devCode2 = this.rtChangeMapper.queryIBAValue(String.valueOf(oid), "devCode");
            JSONObject jsonObject = new JSONObject();
            if (StringUtils.isNotBlank(devCode2)) {
                if (StringUtils.isNotBlank(devCode)) {
                    if (devCode2.startsWith(devCode)) {
                        jsonObject.put("model", productType);
                        jsonObject.put("devCode", devCode2);
                        result.add(jsonObject);
                    }
                } else {
                    jsonObject.put("model", productType);
                    jsonObject.put("devCode", devCode2);
                    result.add(jsonObject);
                }
            }
        }
        return result;
    }

    /**
     * 获取编码或图样代号
     *
     * @param code 编码前几位或完整编码 支持模糊匹配
     * @param type PattenCode 或 MaterialCode ,可为空
     * @return
     */
    @Override
    public List<JSONObject> getMaterialOrDrawNo(String code, String type) {
        List<JSONObject> result = new ArrayList<>();
        //        if (StringUtils.isNotBlank(code)) {
        List<JSONObject> list = null;
        if (StringUtils.isNotBlank(type)) {
            list = this.rtChangeMapper.queryPatternOrMaterialCode(code, type, RTPlmConstant.VIEW_DESIGN);
        } else {
            list = this.rtChangeMapper.queryMaterialCode(code, "", RTPlmConstant.VIEW_DESIGN);
        }
        if (list != null && list.size() > 0) {
            for (JSONObject obj : list) {
                String oid = obj.getString("OID");
                String partnumber = obj.getString("PARTNUMBER");
                String name = obj.getString("NAME");
                String otype = obj.getString("OTYPE");
                List<String> versionList = new ArrayList<>();
                List<DocDetails> oidList1 = this.typlmPartRelObjectService.queryPartRelatedDocInfo(new BigInteger(oid));
                if (CollUtil.isNotEmpty(oidList1)) {
                    for (DocDetails docDetails : oidList1) {
                        String cadType = docDetails.getCadType();
                        if (cadType.contains("二维图纸")) {
                            String BusinessEdition = rtChangeMapper.queryIBAValueByOidAndOtype(docDetails.getOid(), docDetails.getOtype(), "BusinessEdition");
                            if (StringUtils.isNotBlank(BusinessEdition)) {
                                versionList.add(BusinessEdition);
                            }
                        }
                    }
                }
                Map<String, List<String>> ibaMap = typlmAttributeService.getIbaAttributeMap(new BigInteger(oid), otype);
                JSONObject object = new JSONObject();
                object.put("version", CollUtil.isNotEmpty(versionList) ? String.join(",", versionList) : "");
                object.put("number", partnumber);
                object.put("name", name);
                result.add(object);
            }
        }
        //        }
        return result;
    }

    /**
     * 查询受影响的bom
     *
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public List<JSONObject> queryAffectBOM(LinkedHashMap<String, Object> map) throws Exception {
        List<JSONObject> result = new ArrayList<>();
        String CustomerCode = map.get("CustomerCode").toString();//客户
        String devCode = map.get("devCode").toString();//开发令
        String productType = map.get("productType").toString();//机型
        String MaterialCode = map.get("MaterialCode").toString();//查询的图样代号、物料码、标准件
        String ProductCode = map.get("ProductCode").toString();//成品码
        String description = map.get("description").toString();//物料描述
        String partNumber = map.get("partNumber").toString();//解决新增场景下无变更子件匹配
        String changeStyle = map.get("changeStyle").toString();//增加、删除、修改
        String segmNum = "";
        if (map.containsKey("segmNum")) {
            segmNum = map.get("segmNum").toString();//段号
        }
        String type = "";
        if (map.containsKey("type")) {// 类型 图样代号、物料码、标准件
            type = map.get("type").toString();
            type = CommonUtil.convertPartType(type);
        }
        List<JSONObject> materiallist = new ArrayList<>();
        List<JSONObject> list = new ArrayList<>();
        String materialDescription = "";
        PartDetailsVO childVO = null;
        if ("增加".equals(changeStyle)) {
            if (StringUtils.isNotBlank(MaterialCode)) {
                if (StringUtils.isNotBlank(type)) {
                    materiallist.add(this.rtChangeMapper.queryMaterialByCodeAndType(MaterialCode, type, RTPlmConstant.VIEW_DESIGN));
                    if (CollectionUtils.isNotEmpty(materiallist)) {
                        for (JSONObject json : materiallist) {
                            if (json != null) {
                                String code = json.getString("PARTNUMBER");
                                String oid = json.getString("OID");
                                String otype = json.getString("OTYPE");
                                childVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                                materialDescription = childVO.getDescription();
                                list = queryParentProductCodeAndEBOMPart(list, code, "", "", 0, segmNum, type, changeStyle);
                            }
                        }
                    }
                }
            } else {
                List<JSONObject> productList = new ArrayList<>();
                if ("PatternCode".equals(type)) {
                    productList = this.rtChangeMapper.queryProductCodeByIBA(ProductCode, CustomerCode, devCode, productType, "EBOM_NUM");
                } else if ("MaterialCode".equals(type)) {
                    productList = this.rtChangeMapper.queryProductCodeByIBA(ProductCode, CustomerCode, devCode, productType, "ProductCode");
                } else if ("Standard".equals(type)) {
                    List<JSONObject> list1 = this.rtChangeMapper.queryProductCodeByIBA(ProductCode, CustomerCode, devCode, productType, "EBOM_NUM");
                    List<JSONObject> list2 = this.rtChangeMapper.queryProductCodeByIBA(ProductCode, CustomerCode, devCode, productType, "ProductCode");
                    productList.addAll(list1);
                    productList.addAll(list2);
                }
                if (productList != null && productList.size() > 0) {
                    for (JSONObject item : productList) {
                        String oid = item.getString("OID");
                        String otype = item.getString("OTYPE");
                        PartDetailsVO detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                        List<PartDO> childDOList = this.rtChangeMapper.queryChildPart(oid, RTPlmConstant.VIEW_DESIGN);
                        if (!childDOList.stream().anyMatch(partDO -> partDO.getPartnumber().startsWith(partNumber))) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("MaterialCode", partNumber);
                            jsonObject.put("firstParent", detailsVO.getObjectNumber());
                            jsonObject.put("topParent", detailsVO);
                            list.add(jsonObject);
                        } else {
                            throw new Exception("新增子件“" + partNumber + "”已存在在BOM中！");
                        }
                    }
                }
            }
        } else if ("删除".equals(changeStyle) || "修改".equals(changeStyle)) {
            if (StringUtils.isNotBlank(partNumber)) {
                if (StringUtils.isNotBlank(type) && type.equals("PatternCode")) {
//                    materiallist = this.rtChangeMapper.queryMaterialCode(partNumber, "MaterialCode", RTPlmConstant.VIEW_DESIGN);
//                    if (CollectionUtils.isEmpty(materiallist)) {
//                        materiallist = new ArrayList<>();
//                    }
                }
                materiallist.add(this.rtChangeMapper.queryMaterialByCodeAndType(partNumber, type, RTPlmConstant.VIEW_DESIGN));
                if (CollectionUtils.isNotEmpty(materiallist)) {
                    for (JSONObject json : materiallist) {
                        if (json != null) {
                            String code = json.getString("PARTNUMBER");
                            String oid = json.getString("OID");
                            String otype = json.getString("OTYPE");
                            childVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                            Map<String, List<String>> ibaMap = childVO.getIbaAttributeMap();
                            materialDescription = ibaMap.containsKey("Description") ? String.join(",", ibaMap.get("Description")) : "";
                            list = queryParentProductCodeAndEBOMPart(list, code, "", "", 0, segmNum, type, changeStyle);
                        }
                    }
                }
            }
        }

        if (list != null && list.size() > 0) {
            for (JSONObject json : list) {
                PartDetailsVO detailsVO = json.getObject("topParent", PartDetailsVO.class);
                String productCode = detailsVO.getObjectNumber();
                RtChangeLockInfoDO infoDO = new RtChangeLockInfoDO();
                infoDO.setProductCode(productCode);
                List<RtChangeLockInfoDO> lockInfoDOS = rtChangeLockInfoMapper.queryInfoByDO(infoDO);
                String isLock = "否";
                if (CollUtil.isNotEmpty(lockInfoDOS)) {
                    if (lockInfoDOS.stream().anyMatch(lockInfoDO -> lockInfoDO.getIsLock().equals("2"))) {
                        isLock = "是";
                    }
                }
                Map<String, List<String>> ibaMap = detailsVO.getIbaAttributeMap();
                String description2 = ibaMap.containsKey("Description") ? String.join(",", ibaMap.get("Description")) : "";
                if (StringUtils.isNotBlank(description) && StringUtils.isNotBlank(description2)) {
                    if (!description2.contains(description)) {
                        continue;
                    }
                }
                String firstParent = json.getObject("firstParent", String.class);
                MaterialCode = json.getObject("MaterialCode", String.class);
                JSONObject tempJson = new JSONObject();
                tempJson.put("firstParent", firstParent);
                tempJson.put("isLock", isLock);
                tempJson.put("objectid", detailsVO.getOid());
                tempJson.put("objecttype", detailsVO.getOtype());
                tempJson.put("objectversion", detailsVO.getVersion() + "." + detailsVO.getIteration());
                tempJson.put("partType", type);
                tempJson.put("bomType", detailsVO.getTypeName());
                tempJson.put("code", productCode);
                tempJson.put("status", detailsVO.getLifecycleState());
                tempJson.put("MaterialCode", StringUtils.isEmpty(MaterialCode) ? "" : MaterialCode);
                int count = 0;
                String SegmNum = "";
                if (childVO != null) {
                    List<PartUsageLinkDO> linkList = typlmPartUsageLinkService.queryPartUsageLinkByAoidBoid(new BigInteger(detailsVO.getOid()), new BigInteger(childVO.getMasteredoid()));
                    if (linkList != null && linkList.size() > 0) {
                        PartUsageLinkDO linkDO = linkList.get(0);
                        count = linkDO.getAmount().intValue();
                        SegmNum = this.rtChangeMapper.queryIBAValueByOidAndOtype(linkDO.getOid().toString(), linkDO.getOtype(), "SegmNum");
                    }
                }
                tempJson.put("materialDescription", StringUtils.isEmpty(materialDescription) ? "" : materialDescription);
                tempJson.put("count", count == 0 ? "0" : count);
                tempJson.put("SegmNum", StringUtils.isEmpty(SegmNum) ? "" : SegmNum);
                String CustomerCode2 = ibaMap.containsKey("CustomerCode") ? String.join(",", ibaMap.get("CustomerCode")) : "";
                String devCode2 = ibaMap.containsKey(RTPlmConstant.DevelopmentOrder) ? String.join(",", ibaMap.get(RTPlmConstant.DevelopmentOrder)) : "";
                String productType2 = ibaMap.containsKey("productType") ? String.join(",", ibaMap.get("productType")) : "";
                String V2Model = ibaMap.containsKey("V2Model") ? String.join(",", ibaMap.get("V2Model")) : "";
                String isRestructure = ibaMap.containsKey("reform") ? String.join(",", ibaMap.get("reform")) : "";
                String MadeVietnam = ibaMap.containsKey("factory") ? String.join(",", ibaMap.get("factory")) : "";
                String StatusRequireCode = ibaMap.containsKey("StatusRequireCode") ? String.join(",", ibaMap.get("StatusRequireCode")) : "";
                tempJson.put("CustomerCode", StringUtils.isEmpty(CustomerCode2) ? "" : CustomerCode2);
                tempJson.put("MadeVietnam", StringUtils.isEmpty(MadeVietnam) ? "" : MadeVietnam);
                tempJson.put("StatusRequireCode", StringUtils.isEmpty(StatusRequireCode) ? "" : StatusRequireCode);
                tempJson.put("devCode", StringUtils.isEmpty(devCode2) ? "" : devCode2);
                tempJson.put("productType", StringUtils.isEmpty(productType2) ? "" : productType2);
                tempJson.put("V2Model", StringUtils.isEmpty(V2Model) ? "" : V2Model);
                tempJson.put("isRestructure", StringUtils.isEmpty(isRestructure) ? "" : isRestructure);
                tempJson.put("error", "");
                result.add(tempJson);
            }
        }
        return result;
    }

    /**
     * 查询被保存受影响的bom
     *
     * @param map
     * @return
     * @throws Exception
     */
    @Override
    public List<RtChangeaffectAssociatedbomDO> querySaveAffectBOM(LinkedHashMap<String, Object> map) throws Exception {
        List<JSONObject> result = new ArrayList<>();
        String changeNo = map.get("changeNo").toString();//变更单号
//        String devCode = map.get("devCode").toString();//开发令
//        String productType = map.get("productType").toString();//机型
//        String MaterialCode = map.get("MaterialCode").toString();//查询的图样代号、物料码、标准件
//        String ProductCode = map.get("ProductCode").toString();//成品码
//        String description = map.get("description").toString();//物料描述
        String partNumber = map.get("partNo").toString();//解决新增场景下无变更子件匹配
        String segmNum = map.get("segmNum").toString();//段号
        String type = map.get("partType").toString();//标准件、图样代号、物料码
        RtChangeaffectAssociatedbomDO queryDO = new RtChangeaffectAssociatedbomDO();
        queryDO.setChangeno(changeNo);
        queryDO.setPartnumber(partNumber);
        queryDO.setParttype(type);
        queryDO.setSegmNum(segmNum);
        List<RtChangeaffectAssociatedbomDO> associatedBOMDOList = this.rtChangeaffectAssociatedbomMapper.queryByAssociatedbomDO(queryDO);
        if (CollUtil.isNotEmpty(associatedBOMDOList)) {
            for (RtChangeaffectAssociatedbomDO associatedBOMDO : associatedBOMDOList) {
                String productCode = associatedBOMDO.getCode();
                RtChangeLockInfoDO infoDO = new RtChangeLockInfoDO();
                infoDO.setProductCode(productCode);
                List<RtChangeLockInfoDO> lockInfoDOS = rtChangeLockInfoMapper.queryInfoByDO(infoDO);
                String isLock = "否";
                if (CollUtil.isNotEmpty(lockInfoDOS)) {
                    if (lockInfoDOS.stream().anyMatch(lockInfoDO -> "2".equals(lockInfoDO.getIsLock()))) {
                        isLock = "是";
                    }
                }
                associatedBOMDO.setIslock(isLock);
            }
        }
        return associatedBOMDOList;
    }

    /**
     * 根据编码和类型模糊匹配零件编码
     *
     * @param code
     * @param type
     * @return
     */
    @Override
    public List<JSONObject> queryPartNumberByType(String code, String type) {
        List<JSONObject> result = new ArrayList<>();
        if (StringUtils.isNotBlank(code) && StringUtils.isNotBlank(type)) {
            if ("图样代号".equals(type)) {
                type = "PatternCode";
            } else if ("物料码".equals(type)) {
                type = "MaterialCode";
            } else if ("标准件".equals(type)) {
                type = "Standard";
            }
            List<JSONObject> list = this.rtChangeMapper.queryPartNumberByType(code, type, RTPlmConstant.VIEW_DESIGN);
            if (list != null && list.size() > 0) {
                for (JSONObject obj : list) {
                    String iterationid = obj.getString("ITERATIONID");
                    String partnumber = obj.getString("PARTNUMBER");
                    String name = obj.getString("NAME");
                    String version = obj.getString("VERSION");
                    JSONObject object = new JSONObject();
                    object.put("version", version + "." + iterationid);
                    object.put("number", partnumber);
                    object.put("name", name);
                    result.add(object);
                }
            }
        }
        return result;
    }

    /**
     * 根据子件查询所有顶层父物料，包含EBOM和成品BOM
     *
     * @param list
     * @param partNumber
     * @param count
     * @return
     * @throws Exception
     */
    private List<JSONObject> queryParentProductCodeAndEBOMPart(List<JSONObject> list, String partNumber, String MaterialCode, String firstParent, int count, String segmNum, String type, String changeStyle) throws Exception {
        if (count == 0) {
            MaterialCode = partNumber;
        }
        List<JSONObject> paretnList = this.rtChangeMapper.queryParentPart(partNumber, RTPlmConstant.VIEW_DESIGN);
        if (paretnList != null && paretnList.size() > 0) {
            count++;
            if (count > 7) {
                throw new Exception("父物料超出预设阈值，预设阈值为7层，请知悉");
            }
            for (JSONObject obj : paretnList) {
                String oid = obj.getString("OID");
                String otype = obj.getString("OTYPE");
                String linkoid = obj.getString("LINKOID");
                String linkotype = obj.getString("LINKOTYPE");
                PartDetailsVO detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                String SegmNum = this.rtChangeMapper.queryIBAValueByOidAndOtype(linkoid, linkotype, "SegmNum");
                SegmNum = CommonUtil.concatSegmNum(SegmNum);
                String partnumber = obj.getString("PARTNUMBER");
                if (count == 1) {
                    firstParent = partnumber;
                }
                String typeName = detailsVO.getTypeName();
                JSONObject jsonObject = new JSONObject();
                if ("增加".equals(changeStyle)) {
                    if ("PatternCode".equalsIgnoreCase(type)) {
                        //增加子件的场景，检索类型为图样代号的时候，只检索EBOM号
                        if ("EBOM号".equalsIgnoreCase(typeName)) {
                            //无段号则匹配全部
                            jsonObject = new JSONObject();
                            jsonObject.put("MaterialCode", MaterialCode);
                            jsonObject.put("firstParent", firstParent);
                            jsonObject.put("topParent", detailsVO);
                            list.add(jsonObject);
//                            }
                        } else {
                            queryParentProductCodeAndEBOMPart(list, partnumber, MaterialCode, firstParent, count, segmNum, type, changeStyle);
                        }
                    } else if ("MaterialCode".equals(type)) {
                        //检索类型为物料码的时候，只检索成品BOM号
                        if ("成品码".equalsIgnoreCase(typeName)) {
                            jsonObject = new JSONObject();
                            jsonObject.put("MaterialCode", MaterialCode);
                            jsonObject.put("firstParent", firstParent);
                            jsonObject.put("topParent", detailsVO);
                            list.add(jsonObject);
//                            }
                        } else {
                            queryParentProductCodeAndEBOMPart(list, partnumber, MaterialCode, firstParent, count, segmNum, type, changeStyle);
                        }
                    } else if ("Standard".equals(type)) {
                        //检索类型为标准件的时候，检索成品BOM号和EBOM号
                        if ("成品码".equalsIgnoreCase(typeName) || "EBOM号".equalsIgnoreCase(typeName)) {
                            jsonObject = new JSONObject();
                            jsonObject.put("MaterialCode", MaterialCode);
                            jsonObject.put("firstParent", firstParent);
                            jsonObject.put("topParent", detailsVO);
                            list.add(jsonObject);
//                            }
                        } else {
                            queryParentProductCodeAndEBOMPart(list, partnumber, MaterialCode, firstParent, count, segmNum, type, changeStyle);
                        }
                    }
                } else if ("删除".equals(changeStyle) || "修改".equals(changeStyle)) {
                    if ("PatternCode".equalsIgnoreCase(type)) {
                        //删除和替换子件的场景，检索类型为图样代号的时候，检索成品BOM号和EBOM号
                        if ("EBOM号".equalsIgnoreCase(typeName) || "成品码".equalsIgnoreCase(typeName)) {
                            if (StringUtils.isNotEmpty(segmNum)) {
                                //段号匹配
                                if (segmNum.equals(SegmNum)) {
                                    jsonObject = new JSONObject();
                                    jsonObject.put("MaterialCode", MaterialCode);
                                    jsonObject.put("firstParent", firstParent);
                                    jsonObject.put("topParent", detailsVO);
                                    list.add(jsonObject);
                                }
                            } else {
                                //无段号则匹配全部
                                jsonObject = new JSONObject();
                                jsonObject.put("MaterialCode", MaterialCode);
                                jsonObject.put("firstParent", firstParent);
                                jsonObject.put("topParent", detailsVO);
                                list.add(jsonObject);
                            }
                        } else {
                            queryParentProductCodeAndEBOMPart(list, partnumber, MaterialCode, firstParent, count, segmNum, type, changeStyle);
                        }
                        //检索类型为物料码的时候，只检索成品BOM号
                    } else if ("MaterialCode".equals(type)) {
                        if ("成品码".equalsIgnoreCase(typeName)) {
                            if (StringUtils.isNotEmpty(segmNum)) {
                                if (segmNum.equals(SegmNum)) {
                                    jsonObject = new JSONObject();
                                    jsonObject.put("MaterialCode", MaterialCode);
                                    jsonObject.put("firstParent", firstParent);
                                    jsonObject.put("topParent", detailsVO);
                                    list.add(jsonObject);
                                }
                            } else {
                                jsonObject = new JSONObject();
                                jsonObject.put("MaterialCode", MaterialCode);
                                jsonObject.put("firstParent", firstParent);
                                jsonObject.put("topParent", detailsVO);
                                list.add(jsonObject);
                            }
                        } else {
                            queryParentProductCodeAndEBOMPart(list, partnumber, MaterialCode, firstParent, count, segmNum, type, changeStyle);
                        }
                        //检索类型为标准件的时候，检索成品BOM号和EBOM号
                    } else if ("Standard".equals(type)) {
                        if ("成品码".equalsIgnoreCase(typeName) || "EBOM号".equalsIgnoreCase(typeName)) {
                            if (StringUtils.isNotEmpty(segmNum)) {
                                if (segmNum.equals(SegmNum)) {
                                    jsonObject = new JSONObject();
                                    jsonObject.put("MaterialCode", MaterialCode);
                                    jsonObject.put("firstParent", firstParent);
                                    jsonObject.put("topParent", detailsVO);
                                    list.add(jsonObject);
                                }
                            } else {
                                jsonObject = new JSONObject();
                                jsonObject.put("MaterialCode", MaterialCode);
                                jsonObject.put("firstParent", firstParent);
                                jsonObject.put("topParent", detailsVO);
                                list.add(jsonObject);
                            }
                        } else {
                            queryParentProductCodeAndEBOMPart(list, partnumber, MaterialCode, firstParent, count, segmNum, type, changeStyle);
                        }
                    }
                }
            }
        }
        return list;
    }

    /**
     * 根据物料码查询所有受影响的成品码
     *
     * @param list
     * @param partNumber
     * @param count
     * @return
     * @throws Exception
     */
    private List<PartDetailsVO> queryParentProductCodePart(List<PartDetailsVO> list, String partNumber, int count) throws Exception {
        List<JSONObject> paretnList = this.rtChangeMapper.queryParentPart(partNumber, RTPlmConstant.VIEW_DESIGN);
        if (paretnList != null && paretnList.size() > 0) {
            count++;
            if (count > 7) {
                throw new Exception("父物料超出预设阈值，预设阈值为7层，请知悉");
            }
            for (JSONObject obj : paretnList) {
                String oid = obj.getString("OID");
                String otype = obj.getString("OTYPE");
                PartDetailsVO detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                String partnumber = obj.getString("PARTNUMBER");
                String typeName = detailsVO.getTypeName();
                if ("成品码".equalsIgnoreCase(typeName)) {
                    list.add(detailsVO);
                }
                queryParentProductCodePart(list, partnumber, count);
            }
        }
        return list;
    }

    private List<JSONObject> queryParentPartByType(List<JSONObject> list, String partNumber, int count) throws Exception {
        List<JSONObject> paretnList = this.rtChangeMapper.queryParentPartByType(partNumber, "ProductCode", RTPlmConstant.VIEW_DESIGN);
        if (paretnList != null && paretnList.size() > 0) {
            count++;
            if (count > 7) {
                throw new Exception("父物料超出预设阈值，预设阈值为7层，请知悉");
            }
            list.addAll(paretnList);
            for (JSONObject obj : paretnList) {
                String partnumber = obj.getString("PARTNUMBER");
                String oid = obj.getString("OID");
                String otype = obj.getString("OTYPE");
                queryParentPartByType(list, partnumber, count);
            }
        }
        return list;
    }

    /**
     * 获取受影响的模组信息
     *
     * @param list
     * @param partNumber
     * @param partName
     * @param productType
     * @return
     * @throws Exception
     */
    private List queryModuleList(List list, String partNumber, String partName, String parentPartNo, String productType, String devCode) throws Exception {
        if (StringUtils.isNotBlank(productType)) {
            RtCfgStatusDTO dto = new RtCfgStatusDTO();
            dto.setProducttype(productType);
            dto.setDevcode(devCode);
            ResponseResult result = getModuleIdByModelAndDevelopmentOrder(dto);
            if ("SUCCESS".equals(result.getResult())) {
                ArrayList array = (ArrayList) result.getData();
                if (CollectionUtils.isNotEmpty(array)) {
                    TemplateInfoVO templateInfoVO = (TemplateInfoVO) array.get(0);
                    String moduleId = templateInfoVO.getModuleId();
                    if (StringUtils.isBlank(moduleId) || "null".equals(moduleId)) {
                        return list;
                    }
                    JSONObject moduleMaster = this.rtChangeMapper.getObjectByOid("TY_PARTMASTER", moduleId);
                    String moduleNumber = moduleMaster.getString("PARTNUMBER");
                    String typeNumber = "";
                    if (StringUtils.isNotBlank(partNumber)) {
                        typeNumber = partNumber.substring(0, 5);
                    }
                    List<RtCfgMzDO> rtCfgMzDOS = rtCfgMzMapper.selectRtCfgMzByMODULETYPE(moduleNumber);
                    if (CollectionUtils.isNotEmpty(rtCfgMzDOS)) {
                        for (RtCfgMzDO rtCfgMzDO : rtCfgMzDOS) {
                            String content = rtCfgMzDO.getContent();
                            if (content.contains(typeNumber)) {
                                JSONObject json = new JSONObject();
                                json.put("PartCode", partNumber);
                                json.put("PartName", partName);
                                json.put("ModuleNumber", moduleNumber);
                                json.put("AssociatedPartCode", rtCfgMzDO.getContent());
                                json.put("ModuleId", rtCfgMzDO.getModuleid());
                                json.put("ParentPartNo", parentPartNo);
                                list.add(json);
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    public ResponseResult getModuleIdByModelAndDevelopmentOrder(RtCfgStatusDTO dto) throws ParseException {
        String objectNumber = rtCfgStatusInfoMapper.selectMoudleByProductType(STATUS_INFO_PARTTYPE, dto.getProducttype(), STATUS_INFO_DEVCODE, dto.getDevcode());
        List<TemplateInfoVO> oids = new ArrayList<>();
        if (StringUtils.isNotBlank(objectNumber)) {
            List<String> alternateForPartNumbers = Arrays.asList(objectNumber);
            List<AlternateInfoVO> alternateInfoVOS = typlmPartAlternateService.batchQueryAlternates(alternateForPartNumbers);
            for (AlternateInfoVO alternateInfoVO : alternateInfoVOS) {
                TemplateInfoVO templateInfoVO = new TemplateInfoVO(String.valueOf(alternateInfoVO.getAlternateObjectMasterOid()), alternateInfoVO.getAlternatempnname());
                if (templateInfoVO != null) {
                    oids.add(templateInfoVO);
                }
            }
        }
        return ResponseResult.success(oids, "");
    }

    //获取所有认证信息
    private List queryAccreditationList(List list, String partNumber, String type) throws Exception {
        JSONObject jsonObject = this.rtChangeMapper.queryMaterialByCodeAndType(partNumber, type, RTPlmConstant.VIEW_DESIGN);
        if (jsonObject != null) {
            String code = jsonObject.getString("PARTNUMBER");
            List<JSONObject> appointdetailList = dspfAccreditationPatternMapper.selectAccreditationPattern(code);
            for (int j = 0; j < appointdetailList.size(); j++) {
                JSONObject appointdetailDO = appointdetailList.get(j);
                JSONObject json = new JSONObject();
                json.put("patternCode", StringUtils.isEmpty(code) ? "" : code);
                json.put("drawingName", StringUtils.isEmpty(jsonObject.getString("NAME")) ? "" : jsonObject.getString("NAME"));
                json.put("model", StringUtils.isEmpty(appointdetailDO.getString("DEVCODE")) ? "" : appointdetailDO.getString("DEVCODE"));
                json.put("registeredModel", StringUtils.isEmpty(appointdetailDO.getString("MODEL")) ? "" : appointdetailDO.getString("MODEL"));
                json.put("supplier", StringUtils.isEmpty(appointdetailDO.getString("MANUFACTURER_STR")) ? "" : appointdetailDO.getString("MANUFACTURER_STR"));
                list.add(json);
            }
        }
        return list;
    }

    //获取所有指定信息
    private List queryAppointtListList(List list, String partNumber, String type) throws Exception {
        List<JSONObject> matrialList = this.rtChangeMapper.queryMaterialCode(partNumber, type, RTPlmConstant.VIEW_DESIGN);
        if (matrialList != null && matrialList.size() > 0) {
            for (int i = 0; i < matrialList.size(); i++) {
                JSONObject matrialJson = matrialList.get(i);
                String code = matrialJson.getString("PARTNUMBER");
                List<RtZdMxbDO> appointdetailList = rtZdMapper.selectByMaterialcode(code);
                for (int j = 0; j < appointdetailList.size(); j++) {
                    RtZdMxbDO appointdetailDO = appointdetailList.get(j);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("customerCode", StringUtils.isEmpty(appointdetailDO.getCustomerCode()) ? "" : appointdetailDO.getCustomerCode());
                    jsonObject.put("CustomerName", StringUtils.isEmpty(appointdetailDO.getCustomerName()) ? "" : appointdetailDO.getCustomerName());
                    jsonObject.put("DevelopmentOrder", StringUtils.isEmpty(appointdetailDO.getDevCode()) ? "" : appointdetailDO.getDevCode());
                    jsonObject.put("model", StringUtils.isEmpty(appointdetailDO.getProductType()) ? "" : appointdetailDO.getProductType());
                    jsonObject.put("type", "研发");
                    jsonObject.put("materialCode", StringUtils.isEmpty(appointdetailDO.getMaterialCode()) ? "" : appointdetailDO.getMaterialCode());
                    jsonObject.put("MaterialName", StringUtils.isEmpty(appointdetailDO.getPartName()) ? "" : appointdetailDO.getPartName());
                    jsonObject.put("supplierCode", StringUtils.isEmpty(appointdetailDO.getSupplierCode()) ? "" : appointdetailDO.getSupplierCode());
                    jsonObject.put("SupplierName", StringUtils.isEmpty(appointdetailDO.getSupplierName()) ? "" : appointdetailDO.getSupplierName());
                    jsonObject.put("OrderNo", StringUtils.isEmpty(appointdetailDO.getOrderNo()) ? "" : appointdetailDO.getOrderNo());
                    jsonObject.put("OrderItemNumber", StringUtils.isEmpty(appointdetailDO.getOrderItemNo()) ? "" : appointdetailDO.getOrderItemNo());
                    jsonObject.put("SpecifyType", StringUtils.isEmpty(appointdetailDO.getAppointType()) ? "" : appointdetailDO.getAppointType());
                    list.add(jsonObject);
                }
            }
        }
        return list;
    }

    //获取所有受影响的数据
    private List queryAffectList(List list, String partNumber, String type) throws Exception {
        String PatternCode = "";
        JSONObject tempjson = this.rtChangeMapper.queryMaterialByCodeAndType(partNumber, type, RTPlmConstant.VIEW_DESIGN);
        if (tempjson != null) {
            Map<String, String> enmumap = this.typlmEnumerationService.getEnabledEnumItemsMap(Collections.singletonList("BigCustomer")).get("BigCustomer");
            Map<String, PartDetailsVO> tempmap = new HashMap<>();
            String oid = tempjson.getString("OID");
            String otype = tempjson.getString("OTYPE");
            PartDetailsVO detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
            tempmap.put(partNumber + ";;;初始选定的", detailsVO);
            JSONObject jsonObject = new JSONObject();
            String DrawingNumber = rtChangeMapper.queryIBAValue(oid, "3DDrawingNumber");
            String ReferenceDrawingNumber = rtChangeMapper.queryIBAValue(oid, "ReferenceDrawingNumber");
            if (StringUtils.isNotBlank(DrawingNumber)) {
                tempjson = this.rtChangeMapper.queryMaterialByCodeAndType(DrawingNumber, type, RTPlmConstant.VIEW_DESIGN);
                if (tempjson != null && !tempjson.isEmpty()) {
                    oid = tempjson.getString("OID");
                    otype = tempjson.getString("OTYPE");
                    detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                    tempmap.put(DrawingNumber + ";;;3D源图号", detailsVO);
                }
            }
            if (StringUtils.isNotBlank(ReferenceDrawingNumber)) {
                tempjson = this.rtChangeMapper.queryMaterialByCodeAndType(ReferenceDrawingNumber, type, RTPlmConstant.VIEW_DESIGN);
                if (tempjson != null && !tempjson.isEmpty()) {
                    oid = tempjson.getString("OID");
                    otype = tempjson.getString("OTYPE");
                    detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                    tempmap.put(ReferenceDrawingNumber + ";;;被参考图号", detailsVO);
                }
            }
            tempmap = queryParentPartNoEBOM(tempmap, partNumber, 0, "1");
            for (String key : tempmap.keySet()) {
                PartDetailsVO partDetailsVO = tempmap.get(key);
                List<String> versionList = new ArrayList<>();
                List<DocDetails> oidList1 = this.typlmPartRelObjectService.queryPartRelatedDocInfo(new BigInteger(partDetailsVO.getOid()));
                if (oidList1 != null) {
                    for (DocDetails docDetails : oidList1) {
                        String cadType = docDetails.getCadType();
                        if (cadType.contains("二维图纸")) {
                            String BusinessEdition = rtChangeMapper.queryIBAValueByOidAndOtype(docDetails.getOid(), docDetails.getOtype(), "BusinessEdition");
                            if (StringUtils.isNotBlank(BusinessEdition)) {
                                versionList.add(BusinessEdition);
                            }
                        }
                    }
                }
                Map<String, List<String>> ibaMap = partDetailsVO.getIbaAttributeMap();
                String DedicatedSuppliers = ibaMap.containsKey("FirstSupplier") ? String.join(",", ibaMap.get("FirstSupplier")) : "";
                String Description = ibaMap.containsKey("Description") ? String.join(",", ibaMap.get("Description")) : "";
//                String Description = rtChangeMapper.queryIBAValue(partDetailsVO.getOid(), "Description");
                JSONObject json = new JSONObject();
                json.put("code", StringUtils.isEmpty(partDetailsVO.getObjectNumber()) ? "" : partDetailsVO.getObjectNumber());
                json.put("name", StringUtils.isEmpty(partDetailsVO.getName()) ? "" : partDetailsVO.getName());
                json.put("type", "物料码");
                json.put("description", StringUtils.isEmpty(Description) ? "" : Description);
                json.put("relationship", StringUtils.isEmpty(key.split(";;;")[1]) ? "" : key.split(";;;")[1]);
                json.put("VERSION", CollUtil.isNotEmpty(versionList) ? String.join(",", versionList) : "");
                json.put("state", partDetailsVO.getLifecycleState());
                String ManufacturingAttributes = getManufacturingAttributes(partDetailsVO.getObjectNumber());
                json.put("ManufacturingAttributes", StringUtils.isEmpty(ManufacturingAttributes) ? "" : ManufacturingAttributes);
                json.put("ExclusiveSupplier", StringUtils.isEmpty(DedicatedSuppliers) ? "" : DedicatedSuppliers);
                Map<String, String> map = new HashMap<>();
                List<JSONObject> matrialList = this.rtChangeMapper.queryMaterialCode(partNumber, "MaterialCode", RTPlmConstant.VIEW_DESIGN);
                if (matrialList != null && matrialList.size() > 0) {
                    for (int i = 0; i < matrialList.size(); i++) {
                        JSONObject matrialJson = matrialList.get(i);
                        String code = matrialJson.getString("PARTNUMBER");
                        map = getProductCodeByPattenCode(code, 0, "1", map);
                    }
                }
                List<String> modelList = new ArrayList<>();
                List<String> customList = new ArrayList<>();
                List<String> devCodeList = new ArrayList<>();
                if (!map.isEmpty()) {
                    for (String productOid : map.keySet()) {
//                        String model = rtChangeMapper.queryIBAValue(productOid, RTPlmConstant.PRODUCTTYPE);
//                        if (StringUtils.isNotBlank(model)) {
//                            if (!modelList.contains(model)) {
//                                modelList.add(model);
//                            }
//                        }
                        String CustomerCode = rtChangeMapper.queryIBAValue(productOid, "CustomerCode");
                        if (StringUtils.isNotBlank(CustomerCode)) {
                            if (enmumap.containsKey(CustomerCode)) {
                                if (!customList.contains(CustomerCode)) {
                                    customList.add(CustomerCode);
                                }
                            }
                        }
                        String developmentOrder = rtChangeMapper.queryIBAValue(productOid, RTPlmConstant.DevelopmentOrder);
                        if (StringUtils.isNotBlank(developmentOrder)) {
                            if (!devCodeList.contains(developmentOrder)) {
                                devCodeList.add(developmentOrder);
                                JSONObject typeJson = rtChangeMapper.queryMaterialByCodeAndType(developmentOrder, RTPlmConstant.PRODUCTSPECTRUM, RTPlmConstant.VIEW_DESIGN);
                                if (typeJson != null) {
                                    String name = typeJson.getString("NAME");
                                    if (StringUtils.isNotBlank(name)) modelList.add(name);
                                }
                            }
                        }
                    }
                }
                json.put("UsingtheModel", CollUtil.isNotEmpty(modelList) ? String.join(",", modelList) : "");
                json.put("CustomerName", CollUtil.isNotEmpty(customList) ? String.join(",", customList) : "");
                json.put("devCode", CollUtil.isNotEmpty(devCodeList) ? String.join(",", devCodeList) : "");
                String body = converSoureListInputAttr(partDetailsVO.getObjectNumber());
                String sourceStr = commonService.sendPostRequest(sapSourceListUrl, sapSourceListUsername, sapSourceListPassword, body);
                List<String> supplierList = new ArrayList<>();
                List<String> factoryList = new ArrayList<>();
                if (StringUtils.isNotBlank(sourceStr)) {
                    JSONObject obj = JSON.parseObject(sourceStr);
                    Object etobj = obj.get("ET_TAB");
                    if (etobj != null && etobj instanceof JSONObject) {
                        JSONObject obj2 = (JSONObject) etobj;
                        JSONArray obj3 = (JSONArray) obj2.get("item");
                        for (int i = 0; i < obj3.size(); i++) {
                            JSONObject obj4 = (JSONObject) obj3.get(i);
                            String factory = obj4.getString("EKORG");
                            String supplier = obj4.getString("BU_SORT1");
                            if (StringUtils.isNotBlank(factory)) {
                                if (!factoryList.contains(factory)) {
                                    factoryList.add(factory);
                                }
                            }
                            if (StringUtils.isNotBlank(supplier)) {
                                if (!supplierList.contains(supplier)) {
                                    supplierList.add(supplier);
                                }
                            }
                        }
                    }
                }
                json.put("SourceFactory", CollUtil.isNotEmpty(factoryList) ? String.join(",", factoryList) : "");
                json.put("supplier", CollUtil.isNotEmpty(supplierList) ? String.join(",", supplierList) : "");
                list.add(json);
            }
        }
        return list;
    }

    private String converSoureListInputAttr(String partNumber) {
        JSONObject tempJson = new JSONObject();
        tempJson.put("MATNR", partNumber);
        tempJson.put("WERKS", "");
        tempJson.put("LIFNR", "");
        tempJson.put("ZFLAG", "");
        tempJson.put("NOTKZ", "");
        ArrayList list = new ArrayList();
        list.add(tempJson);
        JSONObject tempJson2 = new JSONObject();
        tempJson2.put("item", list);
        JSONObject sourceJson = new JSONObject();
        sourceJson.put("IT_TAB", tempJson2);
        return sourceJson.toString();
    }

    //获取所有受影响的成品码
    private Map<String, String> getProductCodeByPattenCode(String partNumber, int count, String flag, Map<String, String> map) throws Exception {
        List<JSONObject> paretnList = this.rtChangeMapper.queryParentPart(partNumber, RTPlmConstant.VIEW_DESIGN);
        if (paretnList != null && paretnList.size() > 0) {
            count++;
            if (count > 7) {
                throw new Exception("父物料超出预设阈值，预设阈值为7层，请知悉");
            }
            int index = 0;
            for (JSONObject obj : paretnList) {
                index++;
                String oid = obj.getString("OID");
                String otype = obj.getString("OTYPE");
                PartDetailsVO detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                String parentPartNum = obj.getString("PARTNUMBER");
                String key = flag + "." + index;
                String objType = detailsVO.getTypeName();
                if ("成品码".equalsIgnoreCase(objType)) {
                    map.put(oid, parentPartNum);
                }
                getProductCodeByPattenCode(parentPartNum, count, key, map);
            }
        }
        return map;
    }

    //获取制造属性
    private String getManufacturingAttributes(String partNumber) throws Exception {
        List<String> list = new ArrayList<>();
        String ManufacturingAttrs = "";
        List<JSONObject> paretnList = this.rtChangeMapper.queryParentPart(partNumber, RTPlmConstant.VIEW_DESIGN);
        if (paretnList != null && paretnList.size() > 0) {
            for (JSONObject obj : paretnList) {
                String oid = obj.getString("OID");
                String linkoid = obj.getString("LINKOID");
                String linkotype = obj.getString("LINKOTYPE");
                String ManufacturingAttr = this.rtChangeMapper.queryIBAValueByOidAndOtype(linkoid, linkotype, "ManufacturingAttr");
                if (StringUtils.isNotBlank(ManufacturingAttr)) {
                    if (!list.contains(ManufacturingAttr)) {
                        list.add(ManufacturingAttr);
                    }
                }
            }
        }
        if (list.size() > 0) {
            ManufacturingAttrs = String.join(",", list);
        }
        return ManufacturingAttrs;
    }


    //获取不含EBOM号的父物料
    private Map<String, PartDetailsVO> queryParentPartNoEBOM(Map<String, PartDetailsVO> map, String partNumber, int count, String flag) throws Exception {
        List<JSONObject> paretnList = this.rtChangeMapper.queryParentPart(partNumber, RTPlmConstant.VIEW_DESIGN);
        if (paretnList != null && paretnList.size() > 0) {
            count++;
            if (count > 7) {
                throw new Exception("父物料超出预设阈值，预设阈值为7层，请知悉");
            }
            int index = 0;
            for (JSONObject obj : paretnList) {
                index++;
                String oid = obj.getString("OID");
                String otype = obj.getString("OTYPE");
                String linkoid = obj.getString("LINKOID");
                PartDetailsVO detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                String parentPartNum = obj.getString("PARTNUMBER");
                String key = flag + "." + index;
                String objType = detailsVO.getTypeName();
                if (!"EBOM号".equalsIgnoreCase(objType) && !"成品码".equalsIgnoreCase(objType)) {
                    map.put(parentPartNum + ";;;" + count + "级父物料", detailsVO);
                    map = queryParentPartNoEBOM(map, parentPartNum, count, key);
                }
            }
        }
        return map;
    }

    //获取所有受影响的成品BOM
    private void queryProductBOM(JSONObject result, Map<String, Map<String, String>> map, String partNumber, String firstParent, int count, String flag, String type, String parttype) throws Exception {
        List<JSONObject> matrialList = this.rtChangeMapper.queryMaterialCode(partNumber, type, RTPlmConstant.VIEW_DESIGN);
        List<JSONObject> productList = new ArrayList<>();
        List<JSONObject> moduleList = new ArrayList();
        if (matrialList != null && matrialList.size() > 0) {
            for (int i = 0; i < matrialList.size(); i++) {
                JSONObject matrialJson = matrialList.get(i);
                String boid = matrialJson.getString("OID");
                String botype = matrialJson.getString("OTYPE");
                String code = matrialJson.getString("PARTNUMBER");
                String name = matrialJson.getString("NAME");
                String MaterialDescription = rtChangeMapper.queryIBAValueByOidAndOtype(boid, botype, "Description");
                List<JSONObject> paretnList = this.rtChangeMapper.queryParentPart(code, RTPlmConstant.VIEW_DESIGN);
                if (paretnList != null && paretnList.size() > 0) {
                    count++;
                    if (count > 7) {
                        throw new Exception("父物料超出预设阈值，预设阈值为7层，请知悉");
                    }
                    for (JSONObject obj : paretnList) {
//                        index++;
                        String oid = obj.getString("OID");
                        String otype = obj.getString("OTYPE");
                        String linkoid = obj.getString("LINKOID");
                        String linkotype = obj.getString("LINKOTYPE");
                        PartDetailsVO detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                        Map<String, List<String>> parentIbaMap = detailsVO.getIbaAttributeMap();
                        PartUsageLink partUsageLink = this.typlmPartBomService.getPartUsageLinkInfo(new BigInteger(linkoid), linkotype);
                        Map<String, List<String>> usageIbaMap = partUsageLink.getIbaAttributeMap();
                        Map map2 = new HashMap();
                        map2.put("TotalUsage", partUsageLink.getAmount().toString());
                        map2.put("segmentNumber", usageIbaMap.containsKey("SegmNum") ? String.join(",", usageIbaMap.get("SegmNum")) : "");
                        String parentPartNum = obj.getString("PARTNUMBER");
//                        String key = flag + "." + index;
                        String objType = detailsVO.getTypeName();
//                        if (count == 1) {
//                            firstParent = parentPartNum;
//                            JSONObject tempjson = this.rtChangeMapper.queryMaterialByCodeAndType(code, type, RTPlmConstant.VIEW_DESIGN);
//                            String boid = tempjson.getString("OID");
//                            String MaterialDescription = rtChangeMapper.queryIBAValue(boid, "Description");
//                            map2.put("MaterialDescription", MaterialDescription);
//                            map.put(key, map2);
//                        }
                        if ("成品码".equalsIgnoreCase(objType)) {
                            String ProductioninVietnam = parentIbaMap.containsKey("factory") ? String.join(",", parentIbaMap.get("factory")) : "";
                            String StatusRequireTable = parentIbaMap.containsKey("StatusRequireCode") ? String.join(",", parentIbaMap.get("StatusRequireCode")) : "";
                            String customer = parentIbaMap.containsKey("CustomerCode") ? String.join(",", parentIbaMap.get("CustomerCode")) : "";
                            String devCode = parentIbaMap.containsKey("devCode") ? String.join(",", parentIbaMap.get("devCode")) : "";
                            String v2model = parentIbaMap.containsKey("productTypeV2") ? String.join(",", parentIbaMap.get("productTypeV2")) : "";
                            String model = parentIbaMap.containsKey("productType") ? String.join(",", parentIbaMap.get("productType")) : "";
                            if (StringUtils.isNotBlank(model) && StringUtils.isNotBlank(devCode)) {
                                moduleList = queryModuleList(moduleList, partNumber, name, parentPartNum, model, devCode);
                            }
//                            for (String node : map.keySet()) {
//                                if (key.startsWith(node)) {
//                                   Map<String, String> map3 = map.get(node);
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("firstParent", firstParent);
                            jsonObject.put("DevelopmentOrder", devCode);
                            jsonObject.put("FinishedProductCode", StringUtils.isEmpty(detailsVO.getObjectNumber()) ? "" : detailsVO.getObjectNumber());
                            jsonObject.put("objectid", detailsVO.getOid());
                            jsonObject.put("objecttype", detailsVO.getOtype());
                            jsonObject.put("objectversion", detailsVO.getDisplayVersion());
                            jsonObject.put("materialCode", StringUtils.isEmpty(code) ? "" : code);
                            jsonObject.put("v2model", v2model);
                            jsonObject.put("model", model);
                            jsonObject.put("TotalUsage", partUsageLink.getAmount().toString());
                            jsonObject.put("segmentNumber", usageIbaMap.containsKey("SegmNum") ? String.join(",", usageIbaMap.get("SegmNum")) : "");
                            jsonObject.put("MaterialDescription", StringUtils.isEmpty(MaterialDescription) ? "" : MaterialDescription);
                            jsonObject.put("ProductioninVietnam", ProductioninVietnam);
                            jsonObject.put("StatusRequireTable", StatusRequireTable);
                            jsonObject.put("FinishedProductCodesStatus", detailsVO.getLifecycleState());
                            jsonObject.put("customer", customer);
                            jsonObject.put("parttype", parttype);
                            productList.add(jsonObject);
//                                }
//                            }
                        } else {
                            //list = queryProductBOM(list, map, parentPartNum, firstParent, count, key, type);
                        }
                    }
                }
            }
        }
        result.put("FinishedBOM", productList);
        result.put("module", moduleList);
    }

    //获取所有受影响的EBOM
    private List queryEBOM(List list, Map<String, Map<String, String>> map, String partNumber, String firstParent, int count, String flag, String type) throws Exception {
        List<JSONObject> paretnList = this.rtChangeMapper.queryParentPart(partNumber, RTPlmConstant.VIEW_DESIGN);
        if (paretnList != null && paretnList.size() > 0) {
            count++;
            if (count > 7) {
                throw new Exception("父物料超出预设阈值，预设阈值为7层，请知悉");
            }
            int index = 0;
            for (JSONObject obj : paretnList) {
                index++;
                String oid = obj.getString("OID");
                String otype = obj.getString("OTYPE");
                String linkoid = obj.getString("LINKOID");
                String linkotype = obj.getString("LINKOTYPE");
                PartDetailsVO detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                Map<String, List<String>> parentIbaMap = detailsVO.getIbaAttributeMap();
                PartUsageLink partUsageLink = this.typlmPartBomService.getPartUsageLinkInfo(new BigInteger(linkoid), linkotype);
                Map<String, List<String>> usageIbaMap = partUsageLink.getIbaAttributeMap();
                ;
                Map map2 = new HashMap();
                map2.put("TotalUsage", partUsageLink.getAmount().toString());
                map2.put("segmentNumber", usageIbaMap.containsKey("SegmNum") ? String.join(",", usageIbaMap.get("SegmNum")) : "");
                String parentPartNum = obj.getString("PARTNUMBER");
                String key = flag + "." + index;
                String objType = detailsVO.getTypeName();
                if (count == 1) {
                    firstParent = parentPartNum;
                    JSONObject tempjson = this.rtChangeMapper.queryMaterialByCodeAndType(partNumber, type, RTPlmConstant.VIEW_DESIGN);
                    if (tempjson != null) {
                        String boid = tempjson.getString("OID");
                        String MaterialDescription = rtChangeMapper.queryIBAValue(boid, "Description");
                        map2.put("MaterialDescription", MaterialDescription);
                        map.put(key, map2);
                    }
                }
                if ("EBOM号".equalsIgnoreCase(objType)) {
                    Map<String, String> map3 = new HashMap<>();
                    for (String node : map.keySet()) {
                        if (key.startsWith(node)) {
                            map3 = map.get(node);
                            break;
                        }
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("firstParent", firstParent);
                    jsonObject.put("DevelopmentOrder", parentIbaMap.containsKey("devCode") ? String.join(",", parentIbaMap.get("devCode")) : "");
                    jsonObject.put("EBOMnumber", StringUtils.isEmpty(detailsVO.getObjectNumber()) ? "" : detailsVO.getObjectNumber());
                    jsonObject.put("objectid", detailsVO.getOid());
                    jsonObject.put("objecttype", detailsVO.getOtype());
                    jsonObject.put("objectversion", detailsVO.getDisplayVersion());
                    jsonObject.put("PatternCode", StringUtils.isEmpty(partNumber) ? "" : partNumber);
                    jsonObject.put("model", parentIbaMap.containsKey("productType") ? String.join(",", parentIbaMap.get("productType")) : "");
                    jsonObject.put("TotalUsage", StringUtils.isEmpty(map3.get("TotalUsage")) ? "" : map3.get("TotalUsage"));
                    jsonObject.put("segmentNumber", StringUtils.isEmpty(map3.get("segmentNumber")) ? "" : map3.get("segmentNumber"));
                    jsonObject.put("MaterialDescription", StringUtils.isEmpty(map3.get("MaterialDescription")) ? "" : map3.get("MaterialDescription"));
                    jsonObject.put("EBOStatus", detailsVO.getLifecycleState());
                    list.add(jsonObject);
                } else {
                    list = queryEBOM(list, map, parentPartNum, firstParent, count, key, type);
                }
            }
        }
        return list;
    }

    //获取所有关联对象的关联图纸
    private List getAffectDrawingDoc(List list, String key, PartDetailsVO partDetailsVO) throws Exception {
        //查询关联的图纸
        List<DocDetails> oidList1 = this.typlmPartRelObjectService.queryPartRelatedDocInfo(new BigInteger(partDetailsVO.getOid()));
        if (oidList1 != null) {
            for (DocDetails docDetails : oidList1) {
                int islatest = this.rtChangeMapper.judgeObjectIsLatest("ty_caddoc", docDetails.getOid());
                if (islatest == 1) {
                    List<FileDataVO> filelist = docDetails.getPrimaryFileList();
                    String docType = docDetails.getTypeName();
                    String docNo = docDetails.getNumber();
                    String docName = docDetails.getName();
                    String docVer = docDetails.getDisplayVersion();
                    String docStatus = docDetails.getLifecycleStateName();
                    JSONObject jsonObject = new JSONObject();
                    if (filelist != null) {
                        for (FileDataVO fileDataVO : filelist) {
                            String fileName = fileDataVO.getFileName();
                            jsonObject.put("fileName", StringUtils.isEmpty(fileName) ? "" : fileName);
                        }
                    }
                    Map<String, List<String>> ibaMap = docDetails.getIbaAttributeMap();
                    String ExclusiveSupplier = rtChangeMapper.queryIBAValueByOidAndOtype(docDetails.getOid(), docDetails.getOtype(), "ExclusiveSupplier");
                    String BusinessEdition = rtChangeMapper.queryIBAValueByOidAndOtype(docDetails.getOid(), docDetails.getOtype(), "BusinessEdition");
                    jsonObject.put("documentName", docName);
                    jsonObject.put("documentNumber", docNo);
                    jsonObject.put("exclusivesupplier", StringUtils.isNotBlank(ExclusiveSupplier) ? ExclusiveSupplier : "");
                    jsonObject.put("objectid", docDetails.getOid());
                    jsonObject.put("objecttype", docDetails.getOtype());
                    jsonObject.put("objectversion", StringUtils.isEmpty(BusinessEdition) ? "" : BusinessEdition);
                    jsonObject.put("state", StringUtils.isEmpty(docStatus) ? "" : docStatus);
                    jsonObject.put("version", StringUtils.isEmpty(BusinessEdition) ? "" : BusinessEdition);
                    jsonObject.put("relatetype", key.split(";;;")[1]);//关系类型  20251025
                    jsonObject.put("type", StringUtils.isEmpty(docType) ? "" : docType);
                    jsonObject.put("PatternCode", StringUtils.isEmpty(partDetailsVO.getObjectNumber()) ? "" : partDetailsVO.getObjectNumber());
                    list.add(jsonObject);
                }
            }
        }
        //查询关联的描述文档
        List<IdentifierEntity> identifierEntityList = new ArrayList<>();
        identifierEntityList.add(new IdentifierEntity(new BigInteger(partDetailsVO.getOid()), partDetailsVO.getOtype()));
        List<QueryDescribeObjVO> describeObjVOList = this.typlmPartDescribeLinkService.queryPartDescribeDoc(identifierEntityList);
        if (describeObjVOList != null) {
            for (QueryDescribeObjVO queryDescribeObjVO : describeObjVOList) {
                List<ResultEntityVO> describeObjList = queryDescribeObjVO.getDescribeObjList();
                if (describeObjList != null) {
                    for (ResultEntityVO resultEntityVO : describeObjList) {
                        int islatest = this.rtChangeMapper.judgeObjectIsLatest("ty_doc", String.valueOf(resultEntityVO.getOid()));
                        if (islatest == 1) {
                            BigInteger docOid = resultEntityVO.getOid();
                            String oType = resultEntityVO.getOtype();
                            IdentifierEntity entity = new IdentifierEntity(docOid, oType);
                            List<FileDataVO> fileListByEntity = this.fileHandleService.getFileListByEntity(entity);
                            if (fileListByEntity != null) {
                                for (FileDataVO fileDataVO : fileListByEntity) {
                                    String rolekey = fileDataVO.getRolekey();
                                    if ("PRIMARY".equals(rolekey)) {
                                        String docType = resultEntityVO.getTypeDefName();
                                        String docNo = resultEntityVO.getObjectNumber();
                                        String docName = resultEntityVO.getName();
                                        String fileName = fileDataVO.getFileName();
                                        String docStatus = resultEntityVO.getLifecyclestagekeyName();
                                        JSONObject jsonObject = new JSONObject();
                                        jsonObject.put("documentName", docName);
                                        jsonObject.put("documentNumber", docNo);
                                        jsonObject.put("objectid", resultEntityVO.getOid());
                                        jsonObject.put("objecttype", resultEntityVO.getOtype());
                                        jsonObject.put("objectversion", resultEntityVO.getDisplayVersion());
                                        jsonObject.put("fileName", StringUtils.isEmpty(fileName) ? "" : fileName);
                                        jsonObject.put("state", docStatus);
                                        jsonObject.put("version", resultEntityVO.getMajorVersion() + "." + resultEntityVO.getMinorVersion());
                                        jsonObject.put("relatetype", key.split(";;;")[1]);//关系类型  20251025
                                        jsonObject.put("type", StringUtils.isEmpty(docType) ? "" : docType);
                                        jsonObject.put("PatternCode", StringUtils.isEmpty(partDetailsVO.getObjectNumber()) ? "" : partDetailsVO.getObjectNumber());
                                        list.add(jsonObject);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return list;
    }

    //获取所有受影响的图样代号
    private Map<String, PartDetailsVO> getAffectPatternCodes(String oid, String otype, String type) throws Exception {
        Map<String, PartDetailsVO> map = new HashMap();
        PartDetailsVO detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
        map.put(detailsVO.getObjectNumber() + ";;;初始选定的", detailsVO);
        String DrawingNumber = rtChangeMapper.queryIBAValue(oid, "3DDrawingNumber");
        String ReferenceDrawingNumber = rtChangeMapper.queryIBAValue(oid, "ReferenceDrawingNumber");
        JSONObject tempjson = new JSONObject();
        if (StringUtils.isNotBlank(DrawingNumber)) {
            tempjson = this.rtChangeMapper.queryMaterialByCodeAndType(DrawingNumber, type, RTPlmConstant.VIEW_DESIGN);
            if (tempjson != null && !tempjson.isEmpty()) {
                oid = tempjson.getString("OID");
                otype = tempjson.getString("OTYPE");
                detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                map.put(detailsVO.getObjectNumber() + ";;;源3D图号", detailsVO);
            }
        }
        if (StringUtils.isNotBlank(ReferenceDrawingNumber)) {
            tempjson = this.rtChangeMapper.queryMaterialByCodeAndType(ReferenceDrawingNumber, type, RTPlmConstant.VIEW_DESIGN);
            if (tempjson != null && !tempjson.isEmpty()) {
                oid = tempjson.getString("OID");
                otype = tempjson.getString("OTYPE");
                detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                map.put(detailsVO.getObjectNumber() + ";;;被参考图号", detailsVO);
            }
        }
        map = queryParentPartPatternCodes(map, detailsVO.getObjectNumber(), 0, "1");
        return map;
    }

    //获取所有父物料
    private Map<String, PartDetailsVO> queryParentPartPatternCodes(Map<String, PartDetailsVO> map, String partNumber, int count, String flag) throws Exception {
        List<JSONObject> paretnList = this.rtChangeMapper.queryParentPart(partNumber, RTPlmConstant.VIEW_DESIGN);
        if (paretnList != null && paretnList.size() > 0) {
            count++;
            if (count > 7) {
                throw new Exception("父物料超出预设阈值，预设阈值为7层，请知悉");
            }
            int index = 0;
            for (JSONObject obj : paretnList) {
                index++;
                String oid = obj.getString("OID");
                String otype = obj.getString("OTYPE");
                PartDetailsVO detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
                String parentPart = obj.getString("PARTNUMBER");
                String key = flag + "." + index;
                String type = detailsVO.getTypeName();
                if (!"EBOM号".equalsIgnoreCase(type)) {
                    map.put(detailsVO.getObjectNumber() + ";;;" + count + "级父物料", detailsVO);
                } else {
                    map.put(detailsVO.getObjectNumber() + ";;;EBOM号", detailsVO);
                }
                map = queryParentPartPatternCodes(map, parentPart, count, key);
            }
        }
        return map;
    }

    private List<JSONObject> getAffectObject(List<JSONObject> list, String oid, String otype, String type, String ManufacturingAttr) throws Exception {
        PartDetailsVO detailsVO = this.typlmPdmPartService.queryPartDetailsForCO(new BigInteger(oid), otype);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", detailsVO.getNumber());
        jsonObject.put("name", detailsVO.getName());
        jsonObject.put("type", detailsVO.getTypeName());
        jsonObject.put("relationship", type);
        jsonObject.put("VERSION", detailsVO.getVersion() + "." + detailsVO.getIteration());
        jsonObject.put("state", detailsVO.getLifecycleState());
        jsonObject.put("ManufacturingAttributes", StringUtils.isEmpty(ManufacturingAttr) ? "" : ManufacturingAttr);
        jsonObject.put("ExclusiveSupplier", "");
        jsonObject.put("CustomerName", "");
        jsonObject.put("SourceFactory", "");
        jsonObject.put("supplier", "");
        list.add(jsonObject);
        return list;
    }

    private String sendPostRequest(String urlString, String body) {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody requestBody = RequestBody.create(mediaType, body);
        Request request = new Request.Builder().url(urlString).method("POST", requestBody).addHeader("Content-Type", "application/json").build();
        try {
            Response response = client.newCall(request).execute();
            return response.body().string();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}